【问题标题】:Python compare 2 lists by indexPython按索引比较2个列表
【发布时间】:2017-09-24 08:13:48
【问题描述】:

如何遍历两个列表并按索引比较值。我已经尝试过 for 循环和 zip 的使用。

 for a,b in zip(list1,list2):
    if a[0] in b[4]
       print ('found')

编辑

这就是我所追求的

  results = cHandlers.fetchall() #from an sql query
  response = (r.json()) # from a json request
  for u in range(0,3):
     for row in results:
        if (response['data'][u]['item']) == row[3]
           print (found)     

【问题讨论】:

  • 对我来说,您到底想要比较什么并不明显。您能否举一个包含一些数据的示例,并准确显示您希望比较示例数据集中的哪些项目?
  • 添加了一些额外的信息,你会看到谢谢
  • 好的,我有点明白你想要做什么。但是您显示的代码有什么问题?你有错误吗?如果是这样,请给出完整的回溯。你得到错误的结果吗?如果是这样,请给出数据示例,并显示您获得的输出以及您想要的结果。换句话说,您需要包含minimal reproducible example。此外,您已经使用 Python 2 和 Python 3 标签标记了您的问题。通常你只想要其中一个(或者如果版本无关紧要,则都不想要),并且你应该始终包含纯 python 标记。
  • 对不起,你的权利它有效。

标签: python-2.7 python-3.x list loops for-loop


【解决方案1】:

zip 生成一个元组列表(a,b),其中a 是来自list1b 来自list2 的元素。要检查所有元素,您可以执行以下操作

list1 = [1,2,3,5,4]
list2 = [5,3,4,3,4]

for a in zip(list1,list2):
    if a[0] == a[1]:
        print ('found')

要检查特定索引,您可以使用:

zipped = zip(list1,list2)
if zipped[0][0] == zipped[4][1]:
    print ('found')

同样,在 zipped 元组中,元素 0 对应于 list1,元素 1 对应于 list2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 2014-03-13
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多