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

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

python - 我不明白这份清单的理解(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'])

  ask by Jason Lu translate from so

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...