【D2】Python一周入门

本文详细介绍了Python中的四种基本数据类型:元组、列表、字典和集合的特点及使用方法,包括它们的创建、索引、修改等操作,并提供了丰富的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python中的4种基本类型:元组(Tuple)、列表(list)、集合(set)和字典(dict)。

1、元组

Python中的元组(Tuple)类似于Java中的数组,一旦创建了一个 tuple,就不能以任何方式改变它。这点与Python中的字符串类似,所以我们说元组和字符串都是不可变的序列。元组也支持索引和分片操作。定义一个元组使用一对小(圆)括号” ( ) “.
>>> t1=(1,2,"我",4.3)
>>> t1
(1, 2, '我', 4.3)
>>> type(t1)
<class 'tuple'>
>>> t1[0]
1
>>> t1[1:3]
(2, '我')
>>> t1[0:4]
(1, 2, '我', 4.3)
>>> t1[-1]
4.3
>>> t1[-2]
'我'
>>> t2=t1[0:3]
>>> t2
(1, 2, '我')


2、列表

列表是Python中最具灵活性的有序集合对象类型,与字符串不同的是,列表可以包含任何种类的对象:数字、字符串、甚至是其他列表,并且列表都是可变对象,它支持在原处修改的操作。也可以通过指定的索引和分片获取元素,列表就可元组的可变版本。
定义一个列表使用一对中(方)括号” [ ] “。与元组不同的是,列表有一些内置的函数对列表进行增加,修改和删除等操作。

>>> l1=[1,2,"我",3.4]
>>> type(l1)
<class 'list'>
>>> l1.append (3)  # 1.使用append   向 list 的末尾追加单个元素。
>>> l1
[1, 2, '我', 3.4, 3]
>>> l1.append(3)
>>> l1
[1, 2, '我', 3.4, 3, 3]
>>> l1.insert(0,12345)   # 2.使用 insert  将单个元素插入到 list 中。数值参数是插入点的索引
>>> l1
[12345, 1, 2, '我', 3.4, 3, 3]
>>> l1.extend([1,2,3,4,5])    #extend 接受一个参数,这个参数总是一个 list
>>> l1
[12345, 1, 2, '我', 3.4, 3, 3, 1, 2, 3, 4, 5]
>>> len(l1)
12
>>> l1.index(1)  # index 在 list 中查找一个值的首次出现并返回索引值。
1
>>> l1.index(5)
11
>>> l1.index("我")
3
>>> l1.index("斯蒂芬")
Traceback (most recent call last):
  File "<pyshell#96>", line 1, in <module>
    l1.index("斯蒂芬")
ValueError: '斯蒂芬' is not in list

>>> l1

[12345, 1, 2, '我', 3.4, 3, 3, 1, 2, 3, 4, 5]
>>> l1.remove(3)
>>> l1
[12345, 1, 2, '我', 3.4, 3, 1, 2, 3, 4, 5]
>>> l1.remove('我')   # remove 从 list 中 仅仅 删除一个值的首次出现。如果在 list 中没有找到值,Python 会引发一个异常 
>>> l1
[12345, 1, 2, 3.4, 3, 1, 2, 3, 4, 5]
>>> l1.pop()  # pop 它会做两件事:删除 list 的最后一个元素,然后返回删除元素的值。
5
>>> l1
[12345, 1, 2, 3.4, 3, 1, 2, 3, 4]
>>> l1.pop()
4
>>> l1
[12345, 1, 2, 3.4, 3, 1, 2, 3]


3、字典(dict)

字典(Dictionary) 是 Python 的内置数据类型之一,它定义了键和值之间一对一的关系,但它们是以无序的方式储存的。 Python 中的 dictionary 像 Java 中的 Hashtable 类的实例。定义 Dictionary 使用一对大(花)括号” { } ”

>>> d1={'name':'wzl', "age":36, "sex":"Male"}
>>> d1
{'sex': 'Male', 'age': 36, 'name': 'wzl'}
>>> type(d1)
<class 'dict'>
>>> d1['name']="James"
>>> d1
{'sex': 'Male', 'age': 36, 'name': 'James'}
>>> del d1['sex']
>>> d1
{'age': 36, 'name': 'James'}
>>> d1.clear();
>>> d1
{}
 
4、集合(set)

Python的集合(set)和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素。集合对象还支持union(联合)、 intersection(交)、difference(差)和sysmmetric difference(对称差集)等数学运算。由于集合是无序的,所以,sets 不支持 索引、分片、或其它类序列(sequence-like)的操作。集合也存在不可变形式,frozenset为固定集合。

>>> s1={1,2,"我",3.14}
>>> type(s1)
<class 'set'>
>>> l1
[12345, 1, 2, 3.4, 3, 1, 2, 3]
>>> type(l1)
<class 'list'>
>>> s1=set(l1)    #列表强制转换成集合
>>> s1
{12345, 1, 2, 3, 3.4}
>>> type(s1)
<class 'set'>
>>> s1.add(156,"你好")
Traceback (most recent call last):
  File "<pyshell#136>", line 1, in <module>
    s1.add(156,"你好")
TypeError: add() takes exactly one argument (2 given)
>>> s1.add(156)      # 增加元素
>>> s1
{1, 2, 3, 3.4, 12345, 156}
>>> s1.discard(4)
>>> s1
{1, 2, 3, 3.4, 12345, 156}
>>> s1.remove(0)
Traceback (most recent call last):
  File "<pyshell#141>", line 1, in <module>
    s1.remove(0)
KeyError: 0
>>> s1.remove(1)
>>> s1
{2, 3, 3.4, 12345, 156}
>>> s1.remove(15)
Traceback (most recent call last):
  File "<pyshell#144>", line 1, in <module>
    s1.remove(15)
KeyError: 15
>>> s1.remove(156)
>>> s1
{2, 3, 3.4, 12345}
>>> s1.pop()   #随机删除一个元素
2
>>> s1
{3, 3.4, 12345}
>>> s2={2,3,4,"2"}
>>> s1
{3, 3.4, 12345}
>>> s2
{'2', 2, 3, 4}
>>> s3=s1.intersection(s2)    #求交集
>>> s3
{3}
>>> s4=s1.un
Traceback (most recent call last):
  File "<pyshell#154>", line 1, in <module>
    s4=s1.un
AttributeError: 'set' object has no attribute 'un'
>>> s4=s1.union(s2)     #求联合
>>> s4
{'2', 2, 3, 4, 3.4, 12345}
>>> s5=s1.difference(s2)   #求差集
>>> s5
{12345, 3.4}
>>> s5=s1.symmetric_difference(s2)  #求对称差集
>>> s5
{'2', 2, 12345, 4, 3.4}

5、条件语句

(5.1)  if 语句

if和冒号(“:”)之间的内容是   判断条件 ,条件满足,执行:之后的缩进内容

>>> a=2
>>> if a<2:
    print("a<2");
elif a>=2:
    print("a>=2");
  
>>> a=2
>>> if a<2:
    a=a+2;
    print("a<2");
    print("%f" % a);
elif a>=2:
    a=a-2;
    print("a>=2");
    print("%f" % a);
   
a>=2
0.000000

(5.2)  while 语句

>>> i=10;
>>> while i>0 :
    print("Lift off in:")
    print(i)
    i=i-1;

Lift off in:
10
Lift off in:
9
Lift off in:
8
Lift off in:
7
Lift off in:
6
Lift off in:
5
Lift off in:
4
Lift off in:
3
Lift off in:
2
Lift off in:
1

(5.3)  for 语句

>>> a=2;
>>> for a in range(5):
    print(a);
    a=a+1;
    
0
1
2
3
4

>>> a=2
>>> for a in range(500):  #i是index
    print(a);
    a=a+1;
    if a>10:
        print("ok");
        break;

0
1
2
3
4
5
6
7
8
9
10
ok

(5.4)  try exception 语句

当请求字典对象里面没有的key时,python会抛出异常KeyError。

>>> f={"egg":8, "mushroom":20,"pepper":3,"cheese":80}
>>> try:
    if f["egg"]>5:
        print("It's OK");
except(KeyError, TypeError) as error:
    print("Woah! There is no %s" % error);
    
It's OK


>>> try:
    if f["egg"]>10:
        print("It's OK");
except(KeyError, TypeError) as error:
    print("Woah! There is no %s" % error);

>>> a=range(1,10) #生成1:9的序列
>>> a
range(1, 10)
>>> tuple(a)   #序列转换成元组
(1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> list(a)    #序列转换成列表
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> set(a)      #序列转换成集合

{1, 2, 3, 4, 5, 6, 7, 8, 9}

>>> import os   #导入 操作系统相关的  模块,常见模块命令(os/sys/platform)
>>> os.getcwd()
'D:\\Python34'
>>> os.getlogin()
'wangzhenglin'


>>> import random
>>> random.random()  #随机生成一个数字in[0,1] 
0.637733083393377
>>> random.choice(range(0,10))  #在列表0:10中随机选一个
7
>>> random.choice(range(0,10))
5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值