【问题标题】:How to check the list in python [duplicate]如何在python中检查列表[重复]
【发布时间】:2020-01-04 11:35:40
【问题描述】:

它会显示错错正确#如果错误订单显示错误正确订单显示正确

我曾尝试使用嵌套循环来比较元素,但输出显示时间过多,这不是我想要的

     elif first in secList : #if list1 item is in list 2 and order of item are not same

         print("wrong")
     else:

         print("nothing")

【问题讨论】:

  • 您得到三批打印输出的原因是您将list1 中的每个 项与list1 中的每个 项进行比较list2,而您想以相同的速率同时循环播放两者。内置的 zip() 非常适合这一点 - 请参阅下面的答案!

标签: python list


【解决方案1】:

试试这个:

>>> list1= ['black','red','blue']
>>> list2=['red','black','blue']
>>> print(*["correct" if i==j else "wrong" for i,j in zip(list1, list2)], sep='\n')
wrong
wrong
correct

这等价于:

for i,j in zip(list1, list2):
  if i==j:
    print("correct")
  else:
    print("wrong")

for i, j in zip(list1, list2):
    print("correct" if i == j else "wrong")

使用python的zip函数,你可以从多个iterables聚合项目。

【讨论】:

    猜你喜欢
    • 2020-11-07
    • 2017-07-06
    • 2018-02-12
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2022-08-09
    • 2017-07-13
    • 2015-03-20
    相关资源
    最近更新 更多