2017-09-20 49 views
-1

如何打印前3個字符,並且它是數字?如何獲取列表中最常見的元素(Python)

給出的列表:jiuasdi98237657AJJJa9isd9822jjflkgaaiI

的地方,如果格式list1 = ['j', 'i', 'u', 'a' ... ]

輸出:j:6, a:5, i:4

我所做的事情是爲了降低所有

newList = [] 
for count in list1: 
    newList.append(count.lower()) 
+1

爲什麼不使用'計數器'?有什麼限制? –

+0

'鑑於列表:jiuasdi98237657AJJJa9isd9822jjflkgaaiI'你的意思是,這些元素中的每一個都在列表中,比如'list1 = ['j','i','u'...]'因爲你提供的代碼看起來像就像它是一個列表/一個字符串的單個元素一樣。 – RetardedJoker

+0

是的,列表1將會像你給的 – johny

回答

0
import operator 

data = list("kkshdnlsjdhdop;djiee938423jdf") 
# This can be a list or a string result will be the same 

# Making own counter, easier would be to use the collections.Counter though 
counter = {} 
for char in set(data): 
    counter[char] = data.count(char) 

# Getting top 3 counts from the counter 
topCount = dict(sorted(counter.items(), key=operator.itemgetter(1), reverse=True)[:3]) 
print(topCount) 
# Output = {'d': 5, 'j': 3, 'k': 2} 
的情況下

隨着collections.Counter這很簡單:

from collections import Counter 
data = ['k', 'k', 's', 'h', 'd', 'n', 'l', 's', 'j', 'd', 'h', 'd', 'o', 'p', ';', 'd', 'j', 'i', 'e', 'e', '9', '3', '8', '4', '2', '3', 'j', 'd', 'f'] 
print(dict(Counter(data).most_common(3))) 
# Output = {'d': 5, 'j': 3, 'k': 2} 
+0

OP聲明'data'變量是包含每個字符的列表。相應地更新您的代碼。 – RetardedJoker

+0

是的。我的數據在列表中 – johny

+0

在我的回答中,數據也在'list'中,爲了完整起見,我添加了'collections.Counter'方法,因爲它更容易。 – Ludisposed

0

簡單地用收集計數器,

from collections import Counter 

Counter(i for i in list1 if i.isalpha()) 

這將創建字典char類型的值。

相關問題