Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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'])

  ask by Jason Lu translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
339 views
Welcome To Ask or Share your Answers For Others

1 Answer

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您提供两个列表的笛卡尔积:)

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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...