使用for循环合并列表?

时间:2018-10-15 18:42:09

标签: python python-3.x

我在这里有一个代码:

print('Hello Alex! Please tell me how many different shells you collected.')
pukaAlex = int(input('Puka: '))
coneAlex = int(input('Cone: '))
driftwoodAlex = int(input('Driftwood: '))
seaglassAlex = int(input('Sea Glass: '))
starfishAlex = int(input('Starfish: '))
lstAlex = [pukaAlex, coneAlex, driftwoodAlex, seaglassAlex, starfishAlex]

print('Hello Bay! Please tell me how many different shells you collected.')
pukaBay = int(input('Puka: '))
coneBay = int(input('Cone: '))
driftwoodBay = int(input('Driftwood: '))
seaglassBay = int(input('Sea Glass: '))
starfishBay = int(input('Starfish: '))
lstBay = [pukaBay, coneBay, driftwoodBay, seaglassBay, starfishBay]

lstAlexTwo = [('Puka', pukaAlex), ('Cone', coneAlex),
              ('Driftwood', driftwoodAlex), ('Sea Glass', seaglassAlex),
              ('Starfish', starfishAlex)]
lstBayTwo = [('Puka', pukaBay), ('Cones', coneBay),
             ('Driftwood', driftwoodBay), ('Sea Glass', seaglassBay),
             ('Starfish', starfishBay)]

print('Alex\'s List: ', lstAlexTwo)
print('Bay\'s List: ', lstBayTwo)

我知道我还有其他组合列表选项,但是我不确定如何将Alex和Bay列表中的Pukas和Cones数量与 for循环组合在一起创建两者的总和,同时创建一个新列表。

我知道我可以使用+字符将两者相加

示例输出:

[('Puka', 52), ('Cone', 21)] 

假设收集到的Puka总数为52,而Cones为21。

2 个答案:

答案 0 :(得分:0)

这是您可以组合值的方式。然后,您可以做最后的操作,并用新列表中的字符串敲打它们。

newList = []
for i in range(len(lstBay)):
    newList.append(lstBay[i] + lstAlex[i])

答案 1 :(得分:0)

尝试一下:

new_list = [(name, val1+val2) for (name, val1), (_, val2) in zip(lstAlexTwo, lstBayTwo)]