簡體   English   中英

Python 檢查項目是否在列表中

[英]Python check if Items are in list

我正在嘗試遍歷兩個列表並檢查 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)

當前 Output:

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

所需的 Output:

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每個元素打印一個值。

你也可以寫(這與上面的內容相同但是利用了for循環添加else的能力):

for i in list_1:
    for x in list_2:
        if i in x:
            print(x)
            break
    else:
        print(i)
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)

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

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

for i in range(len(list_1)):
  if list_1[i] in list_2[i]:
    print(list_2[i])
  else:
    print(list_1[i])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM