我对python还是很陌生,因此尽管我已经尝试了几个小时了,但是我还是不能解决这个问题。我有一个名为 list_of_tuples 的元组列表,然后还有另一个名为 finalTuple 的元组列表。 并且在其中附加了两个元组。我想做的是从list_of_tuples中读取所有元组,并弄清楚列表中是否已经有相同的元组。 如果有一个,我想在控制台中打印一条消息,指出否则,只需将元组追加到finalTuple中即可。有人可以帮我吗?我已经尝试了以下代码,但没有用:
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:\Users\andri\PythonProjects\mypyth> 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
答案 0 :(得分:1)
您的if
块将检查该值是否已存在,发生在if
块检查该值是否不存在之后,将该值附加到列表中,因此前者始终为{{1 }},因为该值将被附加到列表中,即使它没有被附加。对于相反的情况,应使用True
块。此外,要检查元组列表中是否已存在元组,可以简单地使用else
运算符代替:
in
答案 1 :(得分:0)
lot = [("a","b","c"),
("a","b","c"),
("a","b","d"),
("a","b","d"),
("i","k","l")]
ft = [("a","b","c"),("a","b","d")]
为membership testing使用in
或not 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')]
>>>
或use sets for membership testing。
>>> set(lot).difference(ft)
{('i', 'k', 'l')}
>>> ft.extend(set(lot).difference(ft))
>>> ft
[('a', 'b', 'c'), ('a', 'b', 'd'), ('i', 'k', 'l')]
>>>