Python基础 - 05元祖集合字典
三、元祖
3.1 定义元祖
tup = () print(type(tup)) # <class 'tuple'> tup1 = ('aa') print(type(tup1)) # <class 'str'> tup2 = ('aa',) print(type(tup2)) # <class 'tuple'> 只有一个元素时,加上逗号表示元祖,否则为字符串 tup3 = ('aa','bb') print(type(tup3)) # <class 'tuple'>
aTuple = ('1', 'hello', 'AAA') print(aTuple) # ('1', 'hello', 'AAA') print(aTuple[2]) # AAA print(aTuple[:2]) # ('1', 'hello') print(aTuple[::-1]) # ('AAA', 'hello', '1')
print(aTuple.count('1')) # 1 print(aTuple.index('hello', 1)) # 1 print(aTuple.index('hello')) # 1 aTuple = ('1', 'hello','AAA', 'hello') print(aTuple.index('hello', 2)) # 3,从下标2开始 print(aTuple.index('hello')) # 1,返回第一个遇到的元素位置 t3 = ('A', 'a', 'b', 'c', 'd', 'e', 'd') index = t3.index('d', 1, 7) print(index) # 4
print(len(t3)) # 7 if 'c' in t3: print('存在') else: print('不存在') for i in t3: print(i)
# 元祖转列表 print(list(t3)) # ['A', 'a', 'b', 'c', 'd', 'e', 'd'] list3 = ['1', '2', '3'] print(tuple(list3)) # ('1', '2', '3')
from collections import namedtuple # 命名元祖 NetworkAddress = namedtuple('NetworkAddress',['hostname','port']) a = NetworkAddress('www.python.org', 80) print(a.hostname) print(a.port) print(type(a)) # <class '__main__.NetworkAddress'> print(len(a)) # 2 print(isinstance(a, tuple)) # True
四、集合
4.1 集合定义: 无序不可重复
set1 = {'AAA','AAA'} print(type(set1)) # <class 'set'> print(set1) # {'AAA'} list2 = [1,3,6,5,3,2,4,6,8,6,7,9] set2 = set(list2) print(set2) # {1, 2, 3, 4, 5, 6, 7, 8, 9} set3 = {} print(type(set3)) # <class 'dict'> set4 = set() print(type(set4)) # <class 'set'> print(len(set4)) # 0
4.2 集合的增删改查
set4.add('西游记') print(set4) # {'西游记'} set4.update(set1) print(set4) # {'西游记', 'AAA'} set5 = {'AA','CC','DD','FF'} set5.remove('AA') print(set5) # {'CC', 'DD', 'FF'} # KeyError: 'AA' # set5.remove('AA') del set1 # NameError: name 'set1' is not defined # print(set1) set4.clear() print(set4) # set() # 随机移除 set5.pop() print(set5) # {'CC', 'DD'}
4.3 集合的交集、差集、并集
set2 = {1, 2, 3, 4, 5} set3 = {1, 2, 6, 7, 8, 9} result = set2.intersection(set3) # 交集 print(result) # {1, 2} result = set2.union(set3) # 并集 print(result) # {1, 2, 3, 4, 5, 6, 7, 8, 9} result = set2.difference(set3) # 差集 print(result) # {3, 4, 5} print(set2 & set3) # {1, 2} print(set2 | set3) # {1, 2, 3, 4, 5, 6, 7, 8, 9} print(set2 - set3) # {3, 4, 5}
五、字典
5.1 定义、增删改查
dict1 = {} print(type(dict1)) # <class 'dict'> dict1['name'] = '王路飞' print(dict1) # {'name': '王路飞'} dict1['age'] = 30 dict1['sex'] = '男' print(dict1) # {'name': '王路飞', 'age': 30, 'sex': '男'} # 修改 dict1['age'] = 33 print(dict1) # {'name': '王路飞', 'age': 33, 'sex': '男'} dict1['score'] = 90 print(dict1) # {'name': '王路飞', 'age': 33, 'sex': '男', 'score': 90} dict1['score'] += 5 print(dict1) # {'name': '王路飞', 'age': 33, 'sex': '男', 'score': 95}
# pop(key): 根据key实现删除,删除的是键值对,返回值是key对应的value book = {'name': '《西游记》', 'author': '吴承恩', 'price': 22.38, 'publish': '中信出版社'} r = book.pop('price') print(r) # 22.38 print(book) # {'name': '《西游记》', 'author': '吴承恩', 'publish': '中信出版社'} pub = book.popitem() print(pub) # ('publish', '中信出版社') 最后一个键值对 print(book) # {'name': '《西游记》', 'author': '吴承恩'} del book['author'] # 类似于pop(key) print(book) # {'name': '《西游记》'}
5.2 字典操作
keys() / values() / items() / get() / pop() / popitem() / clear() / copy() / fromkeys(s,t)
value = book.get('name') print(value) # 《西游记》 print(len(book)) # 4 value1 = book.get('key1', 'ABC') print(value1) # None, 没有可以默认返回None; ABC, 指定当key 不存在时的返回值ABC
for i in book: print(i) # name author price publish
print(book.values()) # dict_values(['《西游记》','吴承恩',22.38,'中信出版社']) print(list(book.values())) # ['《西游记》', '吴承恩', 22.38, '中信出版社'] print(book.items()) # dict_items([('name', '《西游记》'), ('author', '吴承恩'), ('price', 22.38), ('publish', '中信出版社')] for i in book.items(): print(i) # ('name', '《西游记》') ('author', '吴承恩') ...... for k, v in book.items(): print(k, v) # name 《西游记》 author 吴承恩 ...... book.setdefault('price', 100) print(book) # {'name': '《西游记》', 'author': '吴承恩', 'price': 22.38, 'publish': '中信出版社'} book.setdefault('page', 780) print(book) # {'name': '《西游记》', 'author': '吴承恩', 'price': 22.38, 'publish': '中信出版社', 'page': 780}
dict1 = {'a': 10, 'b': 20} book.update(dict1) print(book) # {'name': '《西游记》', 'author': '吴承恩', 'price': 22.38, 'publish': '中信出版社', 'page': 780, 'a': 10, 'b': 20} print(dict1) # TypeError: unsupported operand type(s) for +: 'dict' and 'dict' # print(book + dict1)
result = book.fromkeys(dict1) print(result) # {'a': None, 'b': None} result = book.fromkeys(['c', 'd'], [1, 20]) print(result) # {'c': [1, 20], 'd': [1, 20]} result = book.fromkeys(['name', 'ss'], [20, 90]) print(result) # {'name': [20, 90], 'ss': [20, 90]}
del book['name'] print(book) # {'author': '吴承恩', 'price': 22.38, 'publish': '中信出版社', 'page': 780} book.clear() print(book) # {}
字典转列表、元祖
dict1 = {'name': '张三', 'age': 18} result = list(dict1) print(result) # ['name', 'age'] result = tuple(dict1) print(result) # ('name', 'age') list1 = [('a', 10), ('b', 20), ('c', 30)] print(dict(list1)) # {'a': 10, 'b': 20, 'c': 30} list1 = [('a', [1,2,3]), ('b', 20), ('c', 30)] print(dict(list1)) # {'a': [1, 2, 3], 'b': 20, 'c': 30}
六、通用方法
- list: 允许重复,有序, 有下标 []
- tuple: 允许重复,元素不能增加删除修改,只能查看 ()
- dict: 键值对存在, 键:唯一, 值:允许重复 {}
- set: 不允许重复,无序 {}
6.1 通用方法
运算符 | Python表达式 | 结果 | 描述 | 支持的数据类型 |
+ | [1,2]+[3,4] | [1,2,3,4] | 合并 | 字符串,列表,元祖 |
* | ['He']*3 | ['He','He','He'] | 复制 | 字符串,列表,元祖 |
in | 3 in (1,2,3) | True | 元素是否存在 | 字符串,列表,元祖,字典 |
not in | 4 not in (1,2,3) | True | 元素是否不存在 | 字符串,列表,元祖,字典 |
list1 = [1,2,3,5,6,8,9,0] result = max(list1) print(result) # 9 result = min(list1) print(result) # 0 result = sum(list1) print(result) # 34 result = abs(-1) print(result) # 1 t1 = (45,12,78,90,10,88) result = sorted(t1) print(result) # [10, 12, 45, 78, 88, 90] result = sorted(t1, reverse=True) print(result) # [90, 88, 78, 45, 12, 10] result = chr(67) print(result) # C result = ord('A') print(result) # 65
6.2 带下标的遍历
enumerate()类用于将一个可遍历的数据对象(如列表、元祖或字符串)组合成一个索引序列,同时列出数据和数据下标,一般用于for循环中。
chars = ['a', 'b', 'c', 'd'] for i, char in enumerate(chars): print("%d, %s" %(i, char)) # 0, a # 1, b # 2, c # 3, d
6.3 内置方法
print()、 input()、 type()、 id()、 len()、 bin()、 oct()、 hex()、 chr()、 ord()
七、列表推导式: 最终得到一个列表
list1 = [] for i in range(1, 10): list1.append(i) print(list1) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 格式1: list2 = [i for i in range(1, 10)] print(list2) # [1, 2, 3, 4, 5, 6, 7, 8, 9] list3 = [i for i in range(1, 10, 2)] print(list3) # [1, 3, 5, 7, 9] # 格式2: [i for i in 可迭代的 if 条件] list4 = ['62', 'hello', '100', 'world', 'luck', '88'] list5 = [word for word in list4 if word.isalpha()] print(list5) # ['hello', 'world', 'luck'] list6 = [word.title() if word.startswith('h') else word.upper() for word in list4] print(list6) # ['62', 'Hello', '100', 'WORLD', 'LUCK', '88'] a = [(x, y) for x in range(1, 3) for y in range(3)] print(a) # [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] b = [(x, y, z) for x in range(1, 3) for y in range(3) for z in range(4, 6)] print(b) # [(1, 0, 4), (1, 0, 5), (1, 1, 4), (1, 1, 5), (1, 2, 4), (1, 2, 5), (2, 0, 4), (2, 0, 5), (2, 1, 4), (2, 1, 5), (2, 2, 4), (2, 2, 5)] aa = [x for x in range(1, 101)] bb = [aa[i:i + 3] for i in range(0, 101, 3)] print(bb) # [[1, 2, 3], [4, 5, 6],......, [97, 98, 99], [100]] li = [[i, i + 1, i + 2] if i <= 98 else [i for i in range(i, 101)] for i in range(1, 101, 3)] print(li)