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, unt(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: unt(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}
⽅法三
计数器
字符串长度统计
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}]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。