【问题标题】:Comparing each element of a list with each element of another list in Python3在 Python3 中将列表的每个元素与另一个列表的每个元素进行比较
【发布时间】:2019-01-19 10:08:57
【问题描述】:

我有一个列表 --> list_1 = ['a', 'b', 'c']

我还有另一个列表 --> list_2 = ['a', 'x', 'y']

现在,我想比较并检查 list_1 中的每个元素是否存在于 list_2 中。

如何检查?

PS:程序的最终结果是,如果list_1中的元素在list_2中,则执行TASK1,否则执行TASK 2。

【问题讨论】:

  • 顺序重要吗?如果 'a' 在第一个列表中出现两次,在第二个列表中出现一次,是否相等?您可能可以使用集合和==
  • 另外,看看formatting
  • set(list_1).issubset(list_2) 有效地为您提供真假,只要重复无关紧要。
  • @RemcoGerlich 让我们假设两个列表中都没有重复项。

标签: python python-3.x list loops data-structures


【解决方案1】:

您可以使用单词in 来检查一个元素是否在列表中:

list1 = ["a","b","c"]
list2 = ["a","b"]

for i in list1:
    if i in list2:
        # do something
        print (i, "ok")
    else:
        # do something
        print (i, "not found")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-06
    • 2023-03-19
    • 2015-04-02
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    相关资源
    最近更新 更多