【问题标题】:Compare values in 2 lists and import the bigger value in a 3rd list比较 2 个列表中的值并在第 3 个列表中导入较大的值
【发布时间】: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)

标签: python list compare


【解决方案1】:

请注意,更 Pythonic 的方法是:

a = [1, 2, 3]
b = [3, 4, 1]
c = [max(i) for i in zip(a, b)]
print(c)  # [3, 4, 3]

如果两个lists 的项目数量不同,您可以使用zip_longest from itertools

from itertools import zip_longest

a = [1, 2, 3, 7]
b = [3, 4, 1]
c = [max(i) for i in zip_longest(a, b, fillvalue=0)]
print(c)  # [3, 4, 3, 7]

【讨论】:

    【解决方案2】:

    zip你的名单

    In [66]: zip(a, b)
    Out[66]: ((1, 3), (2, 4), (3, 1))
    

    遍历序列,找出压缩后的tuplemax项。

    In [64]: [max(i) for i in zip(a, b)]
    Out[64]: [3, 4, 3]
    

    【讨论】:

      【解决方案3】:

      你需要做myList3.append(myList[i])myList3.append(myList2[i])而不是myList3[i] = myList[i]myList3[i] = myList2[i],因为索引还不存在所以你不能直接分配它

      【讨论】:

      • 我应该在代码中的哪个位置添加这些?我在 for 循环之前尝试过,但仍然出现超出范围的错误
      • 哦,对不起,不是myList3[i] = myList[i] 和它下面的另一个电话
      猜你喜欢
      • 2018-04-24
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多