如何从字符串列表中删除重复项?

时间:2014-11-08 16:21:40

标签: python

我需要这份清单的帮助。我现在不知道如何解决这个问题。

我有这个清单

s = [['aaa', 'bbb'], ['ccc', 'bbb'], ['bbb', 'ddd'], ['fff', 'ddd'], ['ccc', 'eee']]

我想删除此列表中的重复项。

输出必须是:

[['aaa', 'bbb'], ['fff', 'ddd'],['ccc', 'eee']]

2 个答案:

答案 0 :(得分:0)

如何使用以下代码?

s = [['aaa', 'bbb'], ['ccc', 'bbb'], ['bbb', 'ddd'], ['fff', 'ddd'], ['ccc', 'eee']]

def get_unique_pairs(pairs):
    unique_pairs = []
    for pair in pairs:
        unique_pairs_flattened = [x for p in unique_pairs for x in p]
        if not (pair[0] in unique_pairs_flattened or pair[1] in unique_pairs_flattened):
            unique_pairs.append(pair)

    return unique_pairs

print(get_unique_pairs(s))  # => [['aaa', 'bbb'], ['fff', 'ddd'],['ccc', 'eee']]

答案 1 :(得分:-1)

s = [['aaa', 'bbb'], ['ccc', 'bbb'], ['bbb', 'ddd'], ['fff', 'ddd'], ['ccc', 'eee']]

flaten = [ j for i in s for j in i ]
filter_l = list(set(flaten))

res = []
for ele in s:
    if ele[0] in filter_l and ele[1] in filter_l :
        res.append(ele)
        filter_l.remove(ele[0])
        filter_l.remove(ele[1])

print res

output : [['aaa', 'bbb'], ['fff', 'ddd'], ['ccc', 'eee']]

那么可以有更优化的方式来实现它,但这就是我所拥有的。