DAY8容器

列表(list)

1.列表相关运算

1)数学运算: +, *
列表1+列表2 - 将两个列表中的元素合并产生一个新的列表(原列表不会发生改变)
列表*N - 列表中的元素重复N次产生新的列表

list1 = [1, 2, 3]
list2 = ['name', 'age']
new_list = list1 + list2
print(new_list, list1, list2)
print(list1*3)
list3 = [1]*100
print(list3)

2)比较运算: ==, !=

list4 = [1, 2]
print([1, 2] == [2, 1])  # False
print([1, 2] != [2, 1])  # True
print([1, 2] == list4)   # True

, <, >=, <= 只支持相同位置上元素类型相同的两个列表 (了解)

print([1, '2', 3] > [100, 'z'])
# print([1, 2, 3] > ['a', 'b'])   #TypeError: '>' not supported between instances of 'int' and 'str'

2.内置函数

len(列表)、sum(列表) - 要求列表中的元素必须是数字、max(列表)、min(列表)
list(数据) - 将指定数据转换成列表, 所有的序列都可以转换成列表,比如: 字符串,列表、字典、集合、元祖、range、迭代器、生成器等
转换的时候是将序列中的元素作为列表元素

# print(sum(['1', 'abc', 'hj']))
# print(max([1, 'a']))

print(list('abcd'))
print(list(range(5)))
print(list(str(123)))

nums = ['10', '23', '4']   # 10234
print(''.join(nums))

3.相关方法

  1. 列表.count(元素) - 获取指定元素在列表中出现的次数, 结果是整数
print([1, 2, 3, 1, 4].count(1))
  1. 列表.extend(序列) - 将序列中的元素添加到列表中, 结果None
list1 = []
list1.extend('abc')
print(list1)
list1.extend(range(3))
print(list1)
list1.extend(['张飞', '关羽', '赵云'])
print(list1)

list1.extend(['吕布'])
print(list1)

3)列表.index(元素) - 获取指定元素在列表中的下标,如果这个元素有多个只获取第一个,如果元素不存在会报错

list2 = [1, 0, 1, 2, '张飞', '关羽', '赵云', '吕布']
print(list2.index('张飞'))
# print(list2.index('诸葛亮'))    # ValueError: '诸葛亮' is not in list

4)列表.reverse() - 将列表中的元素倒序, 不会产生新列表

list2.reverse()
print(list2)

补充: 内置函数: reversed(序列) - 将序列中的元素倒序产生一个新的迭代器, 原序列不会修改

list1 = [1, 2, 3]
result = reversed('abc')
# for item in result:
#     print(item)
print(list(result))
print(list1)

5)列表.sort() - 对列表中的元素从小到大排序(列表中的元素类型一致并且支持比较运算), 不会产生新的列表

# 列表.sort(reverse=True)   -  从大到小排序
scores = [10, 100, 89, 20, 67, 34, 9]
# scores.sort()
# print(scores)      # python cookbook/ 流畅的python

scores.sort(reverse=True)
print(scores)

6)列表.copy() - 产生一个新的列表,列表中的元素和原列表一样,相当于: 列表[:]

list1 = [1, 2, 3]
list2 = list1
list3 = list1.copy()
print(list2, list3)

list1.append(10)
print(list2, list3)

id(变量) - 查看变量中实质存储的地址
python所有变量实质都是直接保存的数据在内存中的地址

print(id(list1), id(list2), id(list3))

delItem

列表中删除数据
删除列表中所有小于60的数字
问题1: 通过元素删除的时候可能出现删不干净的问题

scores = [10, 50, 90, 89, 45, 70]
for score in scores:
    if score < 60:
        scores.remove(score)

print(scores, score)    # [50, 90, 89, 20, 70]

"""
scores = [10, 50, 90, 89, 45, 70]
score = 10   if 10 < 60    scores.remove(10)   scores = [50, 90, 89, 45, 70]  
score = 90   if 90 < 60
score = 89   if 89 < 60
score = 45   if 45 < 60    scores.remove(45)   scores = [50, 90, 89, 70] 
"""

# 解决问题1:
scores = [10, 50, 90, 89, 45, 70]
scores2 = scores[:]
for score in scores2:
    if score < 60:
        scores.remove(score)
del scores2    # score2只是提供遍历用的,用完后没有其他用处,可以直接删除
print(scores, score)


# 上面的简写
scores = [10, 50, 90, 89, 45, 70]
for score in scores[:]:
    if score < 60:
        scores.remove(score)
print(scores, score)
"""
scores = [10, 50, 90, 89, 45, 70]
scores2 = [10, 50, 90, 89, 45, 70]
score = 10   if 10<60  scores.remove(10)   scores = [50, 90, 89, 45, 70]
score = 50   if 50<60  scores.remove(50)   scores = [90, 89, 45, 70]
score = 90   if 90<60
score = 89   if 89<60
score = 45   if 45<60  scores.remove(45)   scores = [90, 89,70]
score = 70   if 70<60
"""


# 问题2:通过下标删除满足要求的元素的时候,出现下标越界的错误
print('====================问题2=====================')
# scores = [10, 50, 90, 89, 45, 70]
# for index in range(len(scores)):
#     if scores[index] < 60:
#         del scores[index]
#
# print(scores)
"""
scores = [10, 50, 90, 89, 45, 70]
for index in range(6)  
index = range(6)  index = (0,1,2,3,4,5)
index = 0   if scores[0]<60   if 10<60   del scores[0]  scores = [50, 90, 89, 45, 70]
index = 1   if scores[1]<60   if 90<60   
index = 2   if scores[2]<60   if 89<60
index = 3   if scores[3]<60   if 45<60   del scores[3]  scores = [50, 90, 89, 70]
index = 4   if scores[4]<60  (out of range)
"""
# 解决问题2:
scores = [10, 50, 90, 89, 45, 70]
index = 0
while index < len(scores):
    if scores[index] < 60:
        del scores[index]
        continue
    index += 1

print(scores)
"""
scores = [10, 50, 90, 89, 45, 70]   
index = 0
while 0 < 6    if 10<60   del scores[0]   scores = [50, 90, 89, 45, 70] 
while 0 < 5    if 50<60   del scores[0]   scores = [90, 89, 45, 70]
while 0 < 4    if 90<60   index += 1  index = 1
while 1 < 4    if 89<60   index += 1  index = 2
while 2 < 4    if 45<60   del scores[2]   scores = [90, 89,70]
while 2 < 3    if 70<60   index += 1  index = 3  
while 3 < 3 
print(scores)  -  [90, 89,70] 
"""

元祖

1.什么是元祖(tuple):

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

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])

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]))

4.元祖专有特点

1)只有一个元素的元祖, 需要在这个元素的后面加一个逗号

tu1 = ('abc',)
print(type(tu1))

2)元祖的值可以去掉小括号,(直接将多个元素用逗号隔开,也表示一个元祖)

tu2 = 10, 20, 30, 'abc'
print(tu2, type(tu2))
  1. 让变量的个数和元祖中元素的个数保持一致,可以让变量依次取出元祖的中的元素
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

3.2) 通过多个变量去获取元祖元素的时候,可以在某个变量的前面加来将这个变量变成列表获取不带的变量取剩下的数据
注意:这儿带*的变量只能有一个

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)

字典(dict)

1.什么是字典(dict)

字典是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.什么时候用字典

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

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'])

3.查 - 获取字典的值

  1. 获取key对应的值: 字典[key] - 获取字典中指定key对应的值
    注意: 如果key不存在,会报KeyError
dog1 = {'name': '大黄', 'type': '中华田园犬', 'color': 'yellow', 'age': 3}
print(dog1['type'])
# print(dog1['gender'])    # KeyError: 'gender'

获取key对应的值:
字典.get(key) - 获取字典中指定key对应的值, 如果key值不存在返回默认值None
字典.get(key, 默认值) - 获取字典key对应的值,如果key不存在返回指定的默认值
None是python中的关键字,表示数据为空或者没有的意思

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

2)遍历
直接遍历字典拿到是key

dog1 = {'name': '大黄', 'type': '中华田园犬', 'color': 'yellow', 'age': 3}
print('===========遍历===========')
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)

4.增/改 - 添加键值对

字典[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)

5.删

del 字典[key] - 删除字典中key对应的键值对, 如果key不存在会报错

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

字典.pop(key) - 从字典中取出key对应的值,结果是key对应的值

name = film.pop('name')
print(film, name)

6.相关运算

只支持比较运算符

print({'a': 10, 'b': 20} == {'b': 20, 'a': 10})    # True

in / not in
key in 字典 - 判断字典中是否存在某个key对应的键值对

student = {'name': '小明', 'age': 20, 'tel': '16362738493'}
print('小明' in student)   # False
print('name' in student)    # True

len(), max(), min()
dict() - 本身是一个序列,序列中元素是小序列,小序列必须有且只有2个元素,而且这个2个元素中的第一个元素是不可变的
注意:取最大值最小值是取key的最大值和最小值;字典转列表/元祖的时候,是将字典的key取出来作为列表/元祖的元素

print(len(student))
print(max(student))
print(dict(['cb', ['a', 100],  [1000, [1]] ]))
print(list(student))

7.相关方法

1)字典.clear() - 清空字典

student.clear()
print(student)

2)字典.copy() - 复制字典的内容,产生一个新的字典

student = {'name': '小明', 'age': 20, 'tel': '16362738493'}
student1 = student.copy()
student1['name'] = '小花'
print(student)
  1. dict.fromkeys(序列,值) - 创建一个新的字典,将序列中的元素作为新字典的key,指定的值作为每个key对应的值
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)
  1. 字典1.update(字典2) - 将字典2中的键值对添加到字典1中
dict1 = {'a': 10, 'b': 20, 'z': 100}
dict1.update({'c': 30, 'b': 200})
print(dict1)  
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容