如何通过了解元组中的值来查看元组列表是否包含特定元组



我对python相当陌生,因此,尽管我几个小时以来一直在努力寻找解决此问题的方法,但我不能!我有一个名为 list_of_tuples 的元组列表,然后是另一个称为 finalTuple 的元组列表我在其中附加了两个元组。我想做的是从list_of_tuples中读取所有元组,并找出列表中是否已经有一个相同的元组。如果有我想在控制台中打印一条消息,指示否则只需将元组附加到最终元组中即可。有人可以帮助我吗?我尝试了以下代码,但它不起作用:

list_of_tuples = [ ("a","b","c"),
    ("a","b","c"),
    ("a","b","d"),
     ("a","b","d"),
    ("i","k","l")
]
first_tuple = ("a","b","c")
second_tuple= ("a","b","d")
finalTuple = []
finalTuple.append(first_tuple)
finalTuple.append(second_tuple)
for i in range(len(list_of_tuples)):
   # print(listtt[i])
    if not(any((list_of_tuples[i]) in j for j in finalTuple)) :
       key_value = []
       key_value.append(list_of_tuples[i])
       finalTuple.append(tuple(key_value))
       print("The tuple is appended to the list")
    if (any((list_of_tuples[i]) in j for j in finalTuple)) :
       print("The value already exists")

我在控制台上得到的输出是:

PS C:UsersandriPythonProjectsmypyth> py test.py
The tuple is appended to the list
The value already exists
The value already exists
The tuple is appended to the list
The value already exists
The value already exists
The tuple is appended to the list
The value already exists

检查值是否已存在的if块发生在检查值是否存在的if块之后,将值附加到列表中,因此前者始终True因为即使该值不存在,该值也会附加到列表中。您应该改用else块来处理相反的条件。此外,要检查元组列表中是否已存在元组,您只需使用 in 运算符即可:

for i in range(len(list_of_tuples)):
   if list_of_tuples[i] in finalTuple:
       print("The value already exists")
   else:
       finalTuple.append(list_of_tuples[i])
       print("The tuple is appended to the list")
lot = [("a","b","c"),
    ("a","b","c"),
    ("a","b","d"),
     ("a","b","d"),
    ("i","k","l")]
ft = [("a","b","c"),("a","b","d")]

使用 innot in 进行成员资格测试。

>>> for thing in lot:
...     if thing in ft:
...         print(f'{thing} in ft')
...     else:
...         ft.append(thing)

('a', 'b', 'c') in ft
('a', 'b', 'c') in ft
('a', 'b', 'd') in ft
('a', 'b', 'd') in ft
>>> ft
[('a', 'b', 'c'), ('a', 'b', 'd'), ('i', 'k', 'l')]
>>> 

或者使用集进行成员资格测试。

>>> set(lot).difference(ft)
{('i', 'k', 'l')}
>>> ft.extend(set(lot).difference(ft))
>>> ft
[('a', 'b', 'c'), ('a', 'b', 'd'), ('i', 'k', 'l')]
>>>

最新更新