前生篇:zip()并行迭代
[表达式 for item in 可迭代对象 ]
或者:[表达式 for item in 可迭代对象 if 条件判断]
代码演示:
>>> [a for a in range(1,9)]
[1, 2, 3, 4, 5, 6, 7, 8]
>>> [a*2 for a in range(1,9)]
[2, 4, 6, 8, 10, 12, 14, 16]
>>> [a*2 for a in range(1,9) if a%5 == 0]
[10]
>>> [a for a in 'abcdef']
['a', 'b', 'c', 'd', 'e', 'f']
>>> tbs = [(x,y) for x in range(1,8) for y in range(1,10)] # 可以使用两个循环
>>> for tb in tbs:
print(tb)
{key_expression : value_expression for 表达式 in 可迭代对象}
代码演示:
>>> text = 'i love offer,i love studay,i love you'
>>> count = {
a:text.count(a) for a in text}
>>> count
{
'i': 3, ' ': 6, 'l': 3, 'o': 5, 'v': 3, 'e': 4, 'f': 2, 'r': 1, ',': 2, 's': 1, 't': 1, 'u': 2, 'd': 1, 'a': 1, 'y': 2}
>>>
{表达式 for item in 可迭代对象 }
或者:{表达式 for item in 可迭代对象 if 条件判断}
代码演示:
>>> {
x for x in range(1,100) if x%10 == 0}
{
70, 40, 10, 80, 50, 20, 90, 60, 30}
>>>
代码演示:
>>> (x for x in range(1,100) if x%10 == 0)
<generator object <genexpr> at 0x00000225536653C0>
>>>
代码演示:
>>> a = (x for x in range(1,100) if x%10 == 0)
>>> for b in a:
print(b,end='-')
10-20-30-40-50-60-70-80-90-
>>> for b in a:
print(b,end=' ')
>>>
以上帮各位总结好了,收藏,关注即可查收。
前生篇:zip()并行迭代
关注下方公众号,免费拿Python学习资料!!!