Python检查项目是否在列表中 [英] Python check if Items are in list

查看:134
本文介绍了Python检查项目是否在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历两个列表,并检查list_1中的项目是否在list_2中.如果list_1中的项目在list_2中,我想在list_2中打印该项目.如果该项目不在list_2中,那么我想从list_1中打印该项目.下面的代码部分完成了此操作,但是由于我正在执行两个for循环,因此得到了list_1的重复值.您能以Python的方式指导我完成任务吗?

I am trying to iterate through two lists and check if items in list_1 are in list_2. If the item in list_1 is in list_2 I would like to print the item in list_2. If the item is NOT in list_2 I would like print the item from list_1. The below code accomplishes this partially but because I am performing two for loops I am getting duplicate values of list_1. Can you please direct me in a Pythonic way to accomplish?

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

推荐答案

您可以编写:

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中每个元素仅打印一个值.

The approach above ensure that you either print x or i and we only print one value per element in list_1.

您也可以编写(与上面相同,但是利用了在for循环中添加else的功能):

You could also write (which is the same thing as above but makes use of the ability to add an else to a for loop):

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

这篇关于Python检查项目是否在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆