【问题标题】:Python check if Items are in listPython 检查项目是否在列表中
【发布时间】:2017-12-21 04:02:33
【问题描述】:

我正在尝试遍历两个列表并检查 list_1 中的项目是否在 list_2 中。如果 list_1 中的项目在 list_2 中,我想打印 list_2 中的项目。如果该项目不在 list_2 中,我想从 list_1 打印该项目。下面的代码部分地完成了这一点,但是因为我正在执行两个 for 循环,所以我得到了 list_1 的重复值。你能指导我以 Pythonic 的方式完成吗?

list_1 = ['A', 'B', 'C', 'D', 'Y', 'Z']
list_2 = ['Letter A',
          'Letter C',
          'Letter D',
          'Letter H',
          'Letter I',
          'Letter Z']

for i in list_1:
    for x in list_2:
        if i in x:
            print(x)
        else:
            print(i)

电流输出:

Letter A
A
A
A
A
A
B
B
B
B
B
B
C
Letter C
C
C
C
C
D
D
Letter D
D
D
D
Y
Y
Y
Y
Y
Y
Z
Z
Z
Z
Z
Letter Z

期望的输出:

Letter A
B
Letter C
Letter D
Y
Letter Z

【问题讨论】:

  • 当你的循环输出大约是列表的长度相乘时,你如何期望得到 6 行输出?
  • 我的意思是 B。list_1 中的项目。

标签: python list loops


【解决方案1】:

你可以写:

for i in list_1:
    found = False
    for x in list_2:
        if i in x:
            found = True
            break
    if found:
        print(x)
    else:
        print(i)

上述方法确保您打印xi,并且我们只打印list_1 中的每个元素一个值。

您也可以编写(与上述相同,但利用了将else 添加到for 循环的功能):

for i in list_1:
    for x in list_2:
        if i in x:
            print(x)
            break
    else:
        print(i)

【讨论】:

  • 太棒了!正是我想要的。第二种方法是试图实现的目标。感谢您的帮助!
【解决方案2】:
for i in range(len(list_1)):
  if list_1[i] in list_2[i]:
    print(list_2[i])
  else:
    print(list_1[i])

【讨论】:

  • 由于对两个列表使用相同的索引,将大大失败
【解决方案3】:
for i in list_1:
    found = False
    for x in list_2:
        if i in x:
            found = True
            print(x)
    if found == False:
        print(i)

【讨论】:

    【解决方案4】:

    Oneliner:

    [print(i) for i in ["Letter {}".format(i) if "Letter {}".format(i) in list_2 else i for i in list_1]]
    

    输出:

    Letter A
    B
    Letter C
    Letter D
    Y
    Letter Z
    

    【讨论】:

      猜你喜欢
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 2012-06-30
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多