[英]I cannot understand this list comprehension
a = [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
print(a)
the output is ['Python Language', 'Python Programming', 'C Language', 'C Programming']
输出是['Python Language', 'Python Programming', 'C Language', 'C Programming']
I thought that two list added together should be like ['Python ','C ','Language','Programming']
我认为两个列表加在一起应该像['Python ','C ','Language','Programming']
Simply "deconstruct" the comprehension from left to right, it is the same as nesting for
loops to give you the Cartesian product of the two lists:简单地从左到右“解构”理解,它与嵌套for
循环相同, for
您提供两个列表的笛卡尔积:
a = []
for x in ['Python ','C ']:
for y in ['Language','Programming']:
a.append(x+y)
# ['Python Language', 'Python Programming', 'C Language', 'C Programming']
What you had in mind as expected output is the result of a list concatenation like您所想到的预期输出是列表连接的结果,例如
a = ['Python ','C '] + ['Language','Programming']
# ['Python ', 'C ', 'Language', 'Programming']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.