如何在元组的列表中删除元组时,第一个元组的值包含在另一个列表?



我有一个包含元组的列表,我想根据第二个列表中的单词删除包含在元组第一个位置的单词的元组。

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)

输出:

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)]

最新更新