在Python中如何按索引中字母的频率计数

2024-04-25 23:50:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设你给出了5个输入,如下所示:

hello
hullo
zeros

然后它被存储到一个类似so['hello','hullo','zeros']的列表中 我希望它能返回一本字典,计算他们索引中字母的频率。它应该返回这样的结果

{h:2,z:1} {e:2,u:1} {l:2,r:1} {l:2,o:1} {o:2,s:1}

Tags: hello列表字典so字母zeros频率hullo
2条回答

工作zip函数:

for t in zip('123','456','789'):
  print(t)

In the above example zip takes 3 strings as an argument.

1st iteration : when the first time "for" works, zip takes all first elements from each three strings and return it as a tuple => ('1', '4', '7')

2nd iteration zip returns = > ('2', '5', '8')

3rd iteration zip returns => ('3', '6', '9')

for t in zip('123','456','789'):
  print(t)



('1', '4', '7')
('2', '5', '8')
('3', '6', '9')

转到你的问题

s=['你好','你好','零']

*s => will unpack the list into 3 items. 

zip(*s) => zip('hello','hullo','zeros')

for t in zip(*s):

('h', 'h', 'z')
('e', 'u', 'e')
('l', 'l', 'r')
('l', 'l', 'o')
('o', 'o', 's')

你可以试试这个:

s = ['hello','hullo','zeros']
final_data = [{d:''.join(i).count(d) for d in ''.join(i)} for i in zip(*s)]

输出:

[{'h': 2, 'z': 1}, {'u': 1, 'e': 2}, {'r': 1, 'l': 2}, {'l': 2, 'o': 1}, {'s': 1, 'o': 2}]

编辑:函数方法:

def get_count(the_index, the_list):
   listing = [i[the_index] for i in the_list]
   return {a:listing.count(a) for a in listing}

相关问题 更多 >