【发布时间】:2015-04-25 03:39:38
【问题描述】:
我想要列表中不重复的元素。在这里。
A=[1, 2, 3, 2, 5, 1]
所需输出:[3,5]
set() 给[1, 2, 3, 5]
请让我知道完成这项任务。
【问题讨论】:
标签: python
我想要列表中不重复的元素。在这里。
A=[1, 2, 3, 2, 5, 1]
所需输出:[3,5]
set() 给[1, 2, 3, 5]
请让我知道完成这项任务。
【问题讨论】:
标签: python
您可以使用list 对象中的count() 方法获得等于1 的计数:
>>> A=[1, 2, 3, 2, 5, 1]
>>> unique=[i for i in A if A.count(i)==1]
>>> unique
[3, 5]
也可以使用collections 模块中的Counter() 类:
A = [1, 2, 3, 2, 5, 1]
c = Counter(A)
print [key for key, count in c.iteritems() if count==1]
【讨论】:
[ k for k,v in c.items() if v==1 ]
iteritems 会更好。
使用来自collections 的Counter 和defaultdict:
from collections import defaultdict
from collections import Counter
A = [1 ,2 ,3 ,2 ,5, 1]
# create a mapping from each item to it's count
counter = Counter(A)
# now reverse the mapping by using a defaultdict for convenience
countmap = defaultdict(list)
for k, v in counter.iteritems():
countmap[v].append(k)
# take all values that occurred once
print countmap[1] # [3, 5]
如果您对映射感兴趣,可以打印它们:
counter:
Counter({1: 2, 2: 2, 3: 1, 5: 1})
countmap:
defaultdict(<type 'list'>, {1: [3, 5], 2: [1, 2]})
要手动创建计数器,您可以使用此函数:
def make_counter(lst):
counter = dict()
for item in lst:
if item in counter:
counter[item] += 1
else:
counter[item] = 1
return counter
make_counter(A)
输出:
{1: 2, 2: 2, 3: 1, 5: 1}
【讨论】:
#!/usr/bin/python3
from collections import Counter
from functools import reduce
# Initialize Variable
A = [1, 2, 3, 2, 5, 1]
# iterating style
result1 = [key for key, count in Counter(A).items() if count == 1]
# functional style
result2 = reduce(
lambda acc, pair: acc + [pair[0] if pair[1] == 1 else acc,
Counter(A).items(), [])
【讨论】:
普通的普通 python,不需要导入:
使用一个集合来收集您找到的所有元素,删除它们并在再次找到它们时移动到另一个集合 - 这比 Tanveer 建议的使用 count(..) 更快。
A = [1, 2, 3, 2, 5, 1]
found = set()
found_again = set()
for a in A:
if a in found_again:
continue
if a in found:
found.remove(a)
found_again.add(a)
else:
found.add(a)
print(list(found))
输出:
[3,5]
【讨论】:
l1=[1,23,1] l2=[] 对于 l1 中的 i: 如果 l1.count(i)==1: l2.append(i) print("单个元素列表:",l2)
【讨论】:
new = [i for i in A if A.count(i) == 1]
【讨论】: