【问题标题】:how to remove tuple in list into list of tuple in python?如何将列表中的元组删除到python中的元组列表中?
【发布时间】:2021-11-01 17:35:45
【问题描述】:

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

列表到元组列表中:

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

【问题讨论】:

  • 如果有多个选项,应该选择哪个值?另外,请针对不同的问题提出不同的问题。
  • 您现在可以更正代码吗

标签: python-3.x string list indexing tuples


【解决方案1】:

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

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
####

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 2018-12-01
    相关资源
    最近更新 更多