如何在列表中找到副本并使用它们创建另一个列表?如何在Python列表中找到副本并创建另一个副本列表?列表只包含整数。
3 回答
Helenr
TA贡献1780条经验 获得超4个赞
set(a)
a = [1,2,3,2,1,5,6,5,5,5]import collectionsprint [item for item, count in collections.Counter(a).items() if count > 1]## [1, 2, 5]
Counter
set
seen = set()uniq = []for x in a: if x not in seen: uniq.append(x) seen.add(x)
seen = set()uniq = [x for x in a if x not in seen and not seen.add(x)]
not seen.add(x)
add()
None
not
).
seen = {}dupes = []for x in a: if x not in seen: seen[x] = 1 else: if seen[x] == 1: dupes.append(x) seen[x] += 1
a = [[1], [2], [3], [1], [5], [3]]no_dupes = [x for n, x in enumerate(a) if x not in a[:n]]print no_dupes # [[1], [2], [3], [5]] dupes = [x for n, x in enumerate(a) if x in a[:n]]print dupes # [[1], [3]]
MM们
TA贡献1886条经验 获得超2个赞
>>> l = [1,2,3,4,4,5,5,6,1]>>> set([x for x in l if l.count(x) > 1])set([1, 4, 5])
添加回答
举报
0/150
提交
取消