python统计字符串数量

方法一

strings = "Inthisambitiouscooperationprogramagriculturefoodsecurityandoverallsustainableruraltransforma"

strings_count = {}
for s in strings:
    strings_count[s] = strings_count[s] + 1 if s in strings_count else 1
print(sorted(strings_count.items(), key=lambda x: x[1]))

结果:

[('I', 1), ('h', 1), ('y', 1), ('v', 1), ('b', 2), ('p', 2), ('g', 2), ('f', 2), ('d', 2), ('m', 3), ('c', 3), ('n', 5), ('e', 5), ('l', 5), ('s', 6), ('u', 6), ('t', 7), ('i', 7), ('o', 9), ('a', 11), ('r', 11)]

方法二

count() 方法用于统计某个元素在列表中出现的次数。

strings = "Inthisambitiouscooperationprogramagriculturefoodsecurityandoverallsustainableruraltransforma"

strings_count = []
for s in set(strings):
    strings_count.append((s, strings.count(s)))
print(strings_count)

结果:

[('r', 11), ('t', 7), ('h', 1), ('s', 6), ('d', 2), ('v', 1), ('p', 2), ('a', 11), ('o', 9), ('f', 2), ('I', 1), ('y', 1), ('g', 2), ('u', 6), ('c', 3), ('n', 5), ('b', 2), ('e', 5), ('i', 7), ('l', 5), ('m', 3)]

与上面类似的方法还有,如下:

strings = "Inthisambitiouscooperationprogramagriculturefoodsecurityandoverallsustainableruraltransforma"

strings_count = {s: strings.count(s) for s in strings}

print(strings_count)

结果

{'I': 1, 'n': 5, 't': 7, 'h': 1, 'i': 7, 's': 6, 'a': 11, 'm': 3, 'b': 2, 'o': 9, 'u': 6, 'c': 3, 'p': 2, 'e': 5, 'r': 11, 'g': 2, 'l': 5, 'f': 2, 'd': 2, 'y': 1, 'v': 1}

方法三

计数器Counter

import collections

strings = "Inthisambitiouscooperationprogramagriculturefoodsecurityandoverallsustainableruraltransforma"
strings_count = [{key: value} for key, value in collections.Counter(strings).items()]
print(strings_count)

结果:

[{'I': 1}, {'n': 5}, {'t': 7}, {'h': 1}, {'i': 7}, {'s': 6}, {'a': 11}, {'m': 3}, {'b': 2}, {'o': 9}, {'u': 6}, {'c': 3}, {'p': 2}, {'e': 5}, {'r': 11}, {'g': 2}, {'l': 5}, {'f': 2}, {'d': 2}, {'y': 1}, {'v': 1}]
posted @ 2022-03-26 17:59  xyztank  阅读(680)  评论(0编辑  收藏  举报