[英]List Comprehension with two for loops
letters = list('xyz')
pattern = []
for i in range(len(letters)):
for j in range(1,5):
pattern.append(letters[i]*j)
pattern = ['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
How can i write this code in list comprehension format?如何以列表理解格式编写此代码?
You have most of your building blocks, just got to piece it together!您拥有大部分构建块,只需将它们拼凑起来!
letters = list('xyz')
pattern = []
[pattern.append(letters[i]*j) for i in range(len(letters)) for j in range(1,5)]
print(pattern)
['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
[i*j for i in 'xyz' for j in range(1,5)]
For output:对于 output:
['x','y','z','xx','yy','zz','xxx','yyy','zzz']
code:代码:
[l*i for l in 'xyz' for i in range(1,4)]
For output:对于 output:
['x','xx','y','yy','z','zz']
code:代码:
[l*i for i in range(1,3) for l in 'xyz']
for output适用于 output
['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
code ---代码 - -
[i*j for i in 'xyz' for j in range(1,5)]
for output适用于 output
['x', 'y', 'z', 'xx', 'yy', 'zz', 'xxx', 'yyy', 'zzz', 'xxxx', 'yyyy', 'zzzz']
code---代码 - -
[i*j for j in range(1,5) for i in 'xyz']
Just interchange i,j只需交换 i,j
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.