Python(15)--推导

列表推导:

  类似for循环,是从其他列表创建列表的方式

s = [i for i in range(6)]
print(s)    # [0, 1, 2, 3, 4, 5]

  可以加判断条件

s = [i for i in range(6) if i%2 == 0]
print(s)    # [0, 2, 4]

  可以有更多的for

s = [(x, y) for x in range(3) for y in range(3)]
print(s)    # [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

  


  将首字符相同的男孩与女孩名字配对

girls =['alice','bernice','clarice']
boys =['chris', 'arnold', 'bob']
li = [b + "+" + g for b in boys for g in girls if b[0] == g[0]]
print(li)

  上面的效率不高,因为需要检查每一种配对,优化后:

girls =['alice','bernice','clarice']
boys =['chris', 'arnold', 'bob']
d = {}
for girl in girls:
    d.setdefault(girl[0], []).append(girl)
print([b + "+" + g for b in boys for g in d[b[0]]])

# 创建字典d,每项的键都是一个字母,值为这个字母开头的女孩名组成的列表,列表推导遍历男孩,找到名字首字母和当前男孩相同的女孩

 


字典推导:

  字典推导中,for前面有两个用冒号分隔的表达式,分别表示键和值;列表只有一个

d = {i: "{} +1 is {}".format(i, i+1) for i in range(6)}
print(d)
# {0: '0 +1 is 1', 1: '1 +1 is 2', 2: '2 +1 is 3', 3: '3 +1 is 4', 4: '4 +1 is 5', 5: '5 +1 is 6'}

  

  

猜你喜欢

转载自www.cnblogs.com/Mr-chenshuai/p/10034247.html