【问题标题】:Find Duplicates in a list of lists in python在python中的列表列表中查找重复项
【发布时间】:2017-02-28 05:12:39
【问题描述】:
list = [[11], [21], [31], [41], [-11, 21], [11, -21],
        [-21, 31], [21, -31], [-31, 41], [31, -41]]

输出应包含

list_unique = [11,21,31,41]

如何在 python 中为此编写代码?

【问题讨论】:

  • 这个很不清楚。为什么-31-21 在输入中也多次出现时,它们不包含在您的输出中?
  • 这是一个排列问题,所以理想情况下 31 和 -31 是相同的并且是重复的,所以我只需要输出 11,21,31,41 尽管它们出现否定。
  • 那应该是你的问题。请参阅How to ask - 您需要准确说明您要解决的问题、您尝试解决的方法以及您尝试解决的问题。

标签: python-2.7 list dictionary unique


【解决方案1】:

试试这个:

unique_list = []
for i in list:
    for k in i:
        if not abs(k) in unique_list:
            unique_list.append(abs(k))

【讨论】:

  • 对不起。我错过了积极/消极
【解决方案2】:

我可以在这里得到输出是下面的代码:

input_list = [[11], [21], [31], [41], [-11, 21], [11, -21], [-21, 31], [21, -31], [-31, 41], [31, -41]]

def get_explode_list(input_list):
    explode_list = []
    for inner_list in input_list:
        for item in inner_list:
            explode_list.append(item)
    return explode_list

explode_list = get_explode_list(input_list)
dictionary = {}
for x in explode_list:
    value = dictionary.get(x,0)
    value = value+1
    dictionary[x] = value

def get_final_list(dictionary):
    final_list = []
    for key,value in dictionary.items():
        if(value > 1 and key >= 0):
            final_list.append(key)
    return final_list

final_list = get_final_list(dictionary)

final_list = [31, 41, 11, 21] 如果您的输入列表不是 int,您可以使用此代码,只需在 get_final_list 方法中取出 'and key >= 0' 并运行 如果您觉得有帮助,请为答案投票。

【讨论】: