我想在列表中使用非重复元素。在这里。
A=[1, 2, 3, 2, 5, 1]
必需输出:[3,5]
set()
提供[1, 2, 3, 5]
请让我知道完成这项任务。
答案 0 :(得分:2)
您可以使用list对象中的count()
方法获取等于1的计数:
>>> A=[1, 2, 3, 2, 5, 1]
>>> unique=[i for i in A if A.count(i)==1]
>>> unique
[3, 5]
或者,可以使用Counter()
模块中的collections类:
A = [1, 2, 3, 2, 5, 1]
c = Counter(A)
print [key for key, count in c.iteritems() if count==1]
答案 1 :(得分:1)
使用collections
中的<noscript>
和 .hide-div{
width:300px;
display:none;
}
.mybutton:active {
How can I change ".hide-div" "display" value from here?
}
:
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]})
答案 2 :(得分:0)
#!/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(), [])
答案 3 :(得分:0)
普通香草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]