如何将列表中的元组删除到python中的元组列表中?



这里有一个列表到元组列表,需要删除列表中重复的相似值。

list into list:

tup_list = [[('A', '10'), ('B', '28D'), ('C', '14'),('B','70F')], 
[('B', '49C'), ('C', 'T26'), ('D', 'xyz')],
[('A', '24K'), ('C', 'B28'), ('D', '54C')]]

new_lst = []
for tup_l in tup_list:
new_tup_lst = []
for tup in tup_l:
if tup[0] not in new_tup_lst:
new_tup_lst.append(tup)
new_lst.append(new_tup_lst)
print(new_lst)

输出没有变化,请指正。

在元组的第一个列表中,B的元组重复两次。list应该只包含一个B的元组

所需输出:

[[('A', '10'), ('B', '28D'), ('C', '14')], 
[('B', '49C'), ('C', 'T26'), ('D', 'xyz')], 
[('A', '24K'), ('C', 'B28'), ('D', '54C')]]

当您检查新列表中是否已经存在一个字母时,我得到了您的期望。然而,在这一行

if tup[0] not in new_tup_lst:

实际上是在比较字符串"B"与元组('B','70F')。因此,您将永远无法找到匹配。

我有一个解决方案,但由于我对Python有点陌生,这可能不是最好的或最有效的解决方案:

###
### Rest of the code
### 
for tup in tup_l:
# If there's is anything inside new_tup_lst, start comparing
if new_tup_lst:
# Letters will be stored here
letters = []
# For each element contained in new_tup_lst
for element in new_tup_lst:
# Get their letter and add it to letters list
letters.append(element[0])
# If the current tuples letter is not found in letters list
if tup[0] not in letters:
# Add the unique tuple to new_tup_lst
new_tup_lst.append(tup)
# If new_tup_lst is empty, just add the first element
else:
new_tup_lst.append(tup)
####
#### Rest of the code
####

最新更新