Python笔记 - 遍历

/ 技术文章 / 0 条评论 / 510浏览

Python笔记 - 遍历

列表推导式

基本使用:从序列创建列表

list1 = [1,2,3,4]
list2 = [5,6,7,8]

for表达式

[2*x for x in list1]
# [2, 4, 6, 8]

if 表达式

[2*x for x in list1 if x >2]
# [6, 8]

多个for 或 if

[x*y for x in list1 for y in list2]
# [5, 6, 7, 8, 10, 12, 14, 16, 15, 18, 21, 24, 20, 24, 28, 32]

逐一调用

[ list1[i] * list2[i] for i in range(len(list1))]

# [5, 12, 21, 32]

嵌套解析

matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
print(matrix)
# [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

[[row[i] for row in matrix] for i in range(4)]
# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

集合

用大括号({})创建集合。注意:如果要创建一个空集合,你必须用 set() 而不是 {} ;后者创建一个空的字典

set1 = {'H','e','l','l','o'}
set2 = {'W','o','r','l','d'}
set3 = set('Hello World')
print(set1) #集合不重复,无序
#     {'l', 'H', 'o', 'e'}

print(set2)
#     {'l', 'r', 'd', 'W', 'o'}

print(set3)
#     {'l', 'H', 'r', 'd', 'W', ' ', 'o', 'e'}

检测成员

print('H' in set1) # True
print('H' in set2) # False
print('H' in set3) # True
set1 - set2 #差集 在set1中但不在set2中的字母
#     {'H', 'e'}

set1 | set2 #并集
#     {'H', 'W', 'd', 'e', 'l', 'o', 'r'}

set1 & set2 #交集
#     {'l', 'o'}

set1 ^ set2 # 对称差集 在 set1 或 set2 中的字母,但不同时在 set1 和 set2 中
#     {'H', 'W', 'd', 'e', 'r'}

(set1 | set2 ) <= set3 # 包含
#     True

集合推导式

{x for x in set3 if x not in 'abcdefghi'}
#     {' ', 'H', 'W', 'l', 'o', 'r'}

字典遍历

dict1 = {1:'a', 2: 'b', 3: 'c'}

dict1.keys()
#     dict_keys([1, 2, 3])

dict1.values()
#     dict_values(['a', 'b', 'c'])

dict1.items()
#     dict_items([(1, 'a'), (2, 'b'), (3, 'c')])

for key, value in dict1.items():
 print(key, value)
#    1 a
#    2 b
#    3 c

enumerate()获取索引位置和对应值

for index, value in enumerate(dict1.items()):
 print(index, value)

 #  0 (1, 'a')
 #  1 (2, 'b')
 #  2 (3, 'c')

同时遍历两个或更多的序列

questions = ['What\'s your name?', 'How old are you?', 'Where are you come from?']
answers = ['Fun', '18', 'Shanghai']
for q,a in zip(questions, answers):
    print('{0}  {1}.'.format(q,a))

#    What's your name?  Fun.
#    How old are you?  18.
#    Where are you come from?  Shanghai.