请解释为什么此代码可以导致此输出。
首先:
str1 = 'AB'
str2 = '34'
代码是:
[y + x for y in str1 for x in str2]
输出为:
['A3', 'A4', 'B3', 'B4']
我不明白为什么这段代码可以导致此输出。
答案 0 :(得分:1)
代码与运行两个嵌套的for循环并将每个迭代(x + y)插入列表相同。在您的示例中,它将扩展为如下所示:
str1 = 'AB'
str2 = '34'
list = [] # Initialize empty list
for y in str1: # Loop through each character in str1
for x in str2: # Loop through each character in str2
list.append[y + x] # Add character y and character x to the list
print(list) # Shows the output of this list