簡體   English   中英

當第一個元組的值包含在另一個列表中時,如何刪除元組列表中的元組?

[英]How to remove tuples in a list of tuples when the value of the first tuple in contained in an other list?

我有一個包含元組的列表,我想根據第二個列表中的單詞刪除元組的第一個 position 中包含單詞的元組。

list_of_tuples = [
("apple",2),
("banana",54), 
("flower", 5), 
("apple",4), 
("fruit", 3)
]

list_of_words = [
"apple", 
"banana"
]

最終結果應如下所示:

 [("flower", 5), ("fruit", 3)]

這段代碼可以解決問題:

list_of_tuples = [
    ("apple", 2),
    ("banana", 54),
    ("flower", 5),
    ("apple", 4),
    ("fruit", 3)
]

list_of_words = [
    "apple",
    "banana"
]

final_list_of_tuples = [tup for tup in list_of_tuples if tup[0] not in list_of_words]

print(final_list_of_tuples)

一種線性技術稱為列表理解。 您可以在此處找到有關它的更多信息:

Python 列表理解

這里不是完整的解決方案,而是您可以組合起來完成任務的各種操作的細目分類。 希望它能讓您對 Python 構建塊有所了解,您將來可以使用這些構建塊來解決這些類型的問題:

list_of_tuples = [
    ("apple",2),
    ("banana",54), 
    ("flower", 5), 
    ("apple",4), 
    ("fruit", 3)
]

list_of_words = ["apple", "banana"]

# demonstrates tuple unpacking in Python
word, quantity = list_of_tuples[0]
print(word, quantity)

# demonstrates how to test against a collection
print(word in list_of_words)

# demonstrates how to iterate over a list of tuples and unpack
for word, quantity in list_of_tuples:
    print(f"word: {fruit}, quantity: {quantity}")

# demonstrates how to create a new list from an existing list
new_list_of_tuples = []
for word, quantity in list_of_tuples:
    if word != "flower":
        new_list_of_tuples.append((word, quantity))
print(new_list_of_tuples)

Output:

apple 2
True
word: apple, quantity: 2
word: apple, quantity: 54
word: apple, quantity: 5
word: apple, quantity: 4
word: apple, quantity: 3
[('apple', 2), ('banana', 54), ('apple', 4), ('fruit', 3)]

暫無
暫無

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

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