【发布时间】:2017-08-11 09:39:13
【问题描述】:
几天前我开始学习 python 和一般编程只是为了好玩,我遇到了一个小障碍。 我正在尝试比较 2 个用户生成的列表中的值,并在第三个列表中的每个计数器增量之间添加更大的值,例如: a = [1 2 3] b = [3 4 1] 结果应该是 c = [3 4 3]
sa = input("The first list is: ")
myList = list(map(int, sa.split()))
sb = input("The second list is: ")
myList2 = list(map(int, sb.split()))
myList3 = []
i=0
for i in range(len(myList)):
if myList[i] > myList2[i]:
myList3[i] = myList[i]
else: myList3[i] = myList2[i]
print(myList3)
这是我目前的代码,但我收到“IndexError: list assignment index out of range”
【问题讨论】:
-
c = [max(a_item, b_item) for a_item, b_item in zip(a,b)]或list(map(max,a,b)) -
只要
myList的长度大于myList2的长度就会报错 -
OP,注意循环遍历
lists 最好像for item in myList那样完成,或者如果你真的需要索引,for i, item in enumerate(myList)