2017-10-18 28 views
0

實施例的順序的字符:排序變量的使用量(PYTHON)

輸入數據進行排序: 「Hello World」 的 排列:[ 「L」,如圖3所示, 「○」,2「, 「,1,」H「,1,」W「,1,」d「,1,」e「,1,」r「,1] 以ASCII碼的順序 所以我希望它按順序進入表格它出現的次數與角色出現的次數有關。

#Like this 
uncompressedInput = input("Enter data to compress: ") 
# user inputted "abc" 
print("Analysing...") 
#sorted = str.sort(uncompressedInput) 
#print(sorted) 
# ["a", 1, "b", 1, "c", 1] 
+3

的https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python –

+1

可能重複的重複[我如何計算Python中列表項的出現?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in- python) –

回答

2

使用Counter

>>> import collections 
>>> collections.Counter(uncompressedInput).most_common() 
=> [('l', 3), ('o', 2), ('H', 1), ('e', 1), (' ', 1), ('W', 1), ('r', 1), ('d', 1)] 

如果你想在結構酷似如你所說,

排序: 「L」,3, 「O」,2, 「」 ,如圖1所示, 「H」,1, 「W」,1, 「d」,1, 「E」,如圖1所示, 「R」, 1]

>>> l = [] 
>>> [ l.extend([key,val]) for key,val in collections.Counter(s).most_common() ] 
>>> l 
=> ['l', 3, 'o', 2, 'H', 1, 'e', 1, ' ', 1, 'W', 1, 'r', 1, 'd', 1] 

雖然,我不會推薦這樣做,因爲它會對此更加混淆進行進一步的計算。

+0

'計數器'沒有排序,你需要調用'.most_common()' –

+0

忘了補充一點。謝謝@Chris_Rands –

0
import collections 
letters = collections.Counter(uncompressedInput) 
print(letters) 
+0

'collections.Counter'沒有排序 – Adirio

0
from collections import Counter 
[e for x in sorted(Counter("hello world").items(), key=lambda t: t[1], reverse=True) for e in x] 
+0

檢查'collections.Counter.most_common()':https://docs.python.org/3.6/library/collections.html#collections.Counter.most_common – Adirio

+1

Code-只有答案是不鼓勵的。你能說一些爲什麼這個工程按需要嗎? – lit