python語言優點php
表明提示符,等待輸入python指令html
請問Python如何實現將列表:['a','a','b','a','b','c']輸出爲字典:{'a':3,'b':2,'c':1}? 方法一java
str_list = ['a', 'a', 'b', 'a', 'b', 'c']
dic = {}
for name in str_list:
result = dic.get(name, -1)
if result == -1:
dic[name] = 1
else:
dic[name] = dic[name] + 1
print(dic)
複製代碼
方法二python
str_list = ['a', 'a', 'b', 'a', 'b', 'c']
dic = {}
for i in str_list:
if str_list.count(i) >= 1:
dic[i] = str_list.count(i)
print(dic)
複製代碼
方法三web
str_list = ['a', 'a', 'b', 'a', 'b', 'c']
s = set(str_list)
d = dict.fromkeys(s, 0)
for i in s:
d[i] = str_list.count(i)
print(d)
複製代碼