2015-04-25 80 views

回答

1

使用Counterdefaultdictcollections

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} 
+0

好。謝謝。 Wil試試吧.. – learner123

+0

嗨Reut, 我無法使用(計數器): 從集合中導入計數器 因爲我在第三方軟件包Abaqus中使用它作爲腳本。 你是否可以用enumerate()代替counter?? – learner123

+0

@ learner123我添加了代碼來創建一個類似計數器的映射。 –

2

可以使用count()方法從list對象獲得同等的計數,以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] 
+1

這可以工作,但是這反覆遍歷列表...雖然這個例子是一個列表較大的小列表,但這會變得浪費。 –

+0

呀計數器確實有道理。 –

+0

明白了。請記住這一點.. – learner123

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(), []) 
相關問題