day08元组和字典

2019-03-13  本文已影响0人  我去买个橘子o

1. 元组

1.1 什么是元祖(tuple)

元祖就是不可变的列表, 作为序列不可变(不支持增删改)但是有序(支持下标操作)
(元素1, 元素2, 元素3,....) , 元素的要求和列表一样

1.2 查找(获取元素) (和列表一样)

tuple1 = ('abc', 2, 3, 4)
print(tuple1[0], tuple1[-1])
# print(tuple1[10])   # IndexError: tuple index out of range
print(tuple1[0:5:2])
for item in tuple1:
    print(item)

for index in range(len(tuple1)):
    print(index, tuple1[index])

1.3 数学运算、比较运算、in/not in、 len(), max(), min(), sum(), tuple()和对应的列表操作是一样的

print((1, 2, 3)+('a', 'b', 'c'))
print((1, 2, 3) * 2)
print(100 in (1, 2, 3))
print(tuple('abcd'), tuple(range(4)), tuple(['abc', 100]))

1.4 元组专有的特点

tu1 = ('abc',)
print(type(tu1))
tu2 = 10, 20, 30, 'abc'
print(tu2, type(tu2))
point = (100, 200)
x, y = point
print(x, y)

x, y = (100, 200)
x, y = 100, 200

a = 10
b = 20
a, b = (b, a)       # a, b = (b,a) = (20, 10)  a = 20, b=10
student = ('小明', 30, 60, 50, 100, 175)
name, age, *scores, height = student
print(name, scores)

name, *x = student
print(name, x)

*x, y, z = student
print(x, y)

2. 字典(dict)

2.1 什么是字典

字典是python内置的一个容器型数据类型, 可变(支持增删改)、无序(不支持下标操作)
{键1:值1, 键2:值2, 键3:值3,....} 键:值 -> 键值对
键(key): a.不可变 b.唯一 (实际开发建议用字符串)
值(value): 和列表元素的要求一样
注意: 键值对是成对出现;字典存数据,实质要存的是值,键是值的索引

dict1 = {'a': 100, 'b': 'abc', 'c': [1, 2], 'd': {'a': 100}}
print(dict1)

dict1 = {'a': 100, 'b': 'abc', 'a': [1, 2]}
print(dict1)   # {'a': [1, 2], 'b': 'abc'}

2.2 什么时候用字典

如果同时保存的多个数据是具有相同意义的数据,用列表;如果同时保存的多个数据的意义不同,就使用字典

person1 = ['余婷', 18, 100, 40, 155, 50]
person2 = {'name': '余婷', 'age': 18, 'score': 100, 'height': 155, 'weight': 50}
print(person1[0])
print(person2['name'])

allstudents = [
                {'name': '张三', 'age': 18, 'tel': '110', 'dog':{'sex': '母狗', 'color': '白色', 'name': '大黄'}},
                {'name': '小明', 'age': 20, 'tel': '220'},
                {'name': '张三', 'age': 18, 'tel': '110'}
               ]

print(allstudents[0]['dog']['color'])

2.3 查找(获取)字典的值

使用方法 字典[key] 获取字典中指定key对应的值
注意: 如果key不存在,会报KeyError

dog1 = {'name': '大黄', 'type': '中华田园犬', 'color': 'yellow', 'age': 3}
print(dog1['type'])
# print(dog1['gender'])    # KeyError: 'gender'

2.4 获取key对应的值:

print(dog1.get('color'))
print(dog1.get('gender'))
print(dog1.get('gender', '公狗'))

2.5 遍历

直接遍历字典拿到是key

dog1 = {'name': '大黄', 'type': '中华田园犬', 'color': 'yellow', 'age': 3}
print('===========遍历1===========')
for key in dog1:
    print(key, dog1[key])

遍历字典选第一种方法,后面的方法要看得懂

print('===========遍历2===========')
print(dog1.values())
for value in dog1.values():
    print(value)

print('===========遍历3===========')
for key in dog1.keys():
    print(key)

print('===========遍历4===========')
print(dog1.items())
for key, value in dog1.items():
    print(key, value)

2.6 增/改 - 添加键值对

字典[key] = 值 当key不存在的时候就是添加键值对;当key存在的时候,就是修改key对应的值

film = {'name': '流浪地球', '主演': '吴京', 'time': '2019-2-5'}
film['票房'] = '40亿'
print(film)

film['time'] = '2019-2-6'
print(film)

film.setdefault('a', 10)
print(film)

# 字典.setdefault(key, value)   - 只能条件键值对,不能修改
film.setdefault('name', '战狼2')
print(film)

2.7 删

film = {'name': '流浪地球', '主演': '吴京', 'time': '2019-2-5'}
del film['time']
print(film)
name = film.pop('name')
print(film, name)

2.8 相关运算

只支持比较运算符

print({'a': 10, 'b': 20} == {'b': 20, 'a': 10})    # True
print(len(student))
print(max(student))
print(dict(['cb', ['a', 100],  [1000, [1]] ]))
print(list(student))

2.9 相关方法

student.clear()
print(student)
student = {'name': '小明', 'age': 20, 'tel': '16362738493'}
student1 = student.copy()
student1['name'] = '小花'
print(student)
new_dict = dict.fromkeys(['name', 'age', 'gender'], None)
print(new_dict)

person_keys = ['name', 'age', 'gender']
person1 = dict.fromkeys(person_keys, None)
person2 = dict.fromkeys(person_keys, None)
dict1 = {'a': 10, 'b': 20, 'z': 100}
dict1.update({'c': 30, 'b': 200})
print(dict1)  
上一篇下一篇

猜你喜欢

热点阅读