python——元组和字典类型简明理解

元组类型:

元祖创建:

不需要括号可以但是一个元素就当成了字符串类型了

>>> tup1="a";

>>> type(tup1)

<class 'str'>

>>> tup2="a","b";

>>> type(tup2)

<class 'tuple'>

>>> tup3=(1,2,3,4);

>>> tup3

(1, 2, 3, 4)

>>> tup4=('zx','xkd',100)

>>> tup4

('zx', 'xkd', 100)

 

空元祖类型创建:

>>> tup=()

>>> tup

()

创建一个元素的元祖:

元祖是一个元素时元素后面须有一个,号,不然就当作整形处理

>>> tup=(30)

>>> tup

30

>>> type(tup)

<class 'int'>

>>> tup=(20,)

>>> type(tup)

<class 'tuple'>

 

元组修改:

元组元素是不允许修改的,但可以进行元组的连接组合

>>> tup=(1,2,3)

>>> tup1=(2,3,4)

>>> tup2=tup+tup1

>>> print(tup2)

(1, 2, 3, 2, 3, 4)

 

元组的删除:

>>> tup

(1, 2, 3)

>>> del tup

>>> tup

Traceback (most recent call last):

  File "<pyshell#6>", line 1, in <module>

    tup

NameError: name 'tup' is not defined

字典类型:

dict = {'Name': 'zx', 'Age': 7, 'Class': 'First','Name': 'xkd'}
print ("dict['Name']: ", dict['Name'])#不允许同一个键被赋值两次,如果赋值则后一个被记住
dict['Age'] = 8;               # 更新 Age
dict['School'] = "haha"  # 添加信息

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
del dict['Name']
print('输出删除后的字典:',dict)
dict.clear() #清空字典
print('输出清空后的字典:',dict)
del dict # 删除字典
print('输出删除后的字典:',dict)
print('输出删除后的字典某键值对:',dict[age]) #出错 因为字典不存在

输出:

dict['Name']:  xkd
dict['Age']:  8
dict['School']:  haha
输出删除后的字典: {'Age': 8, 'Class': 'First', 'School': 'haha'}
输出清空后的字典: {}
输出删除后的字典: <class 'dict'>
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\2.py", line 15, in <module>
    print('输出删除后的字典某键值对:',dict[age]) #出错 因为字典不存在
NameError: name 'age' is not defined

猜你喜欢

转载自blog.csdn.net/qq_37857219/article/details/80628614
今日推荐