Python: count occurrences in a list using dict comprehension/generator

后端 未结 3 787
长情又很酷
长情又很酷 2020-12-05 21:38

I want to write some tests to analyse the efficiency of different operations in python, namely a comparison of dictionary comprehensions and dict generators.

To test

3条回答
  •  -上瘾入骨i
    2020-12-05 22:09

    You can do it this way:

    >>> words=['this','that','is','if','that','is','if','this','that']
    >>> {i:words.count(i) for i in words}
    {'this': 2, 'is': 2, 'if': 2, 'that': 3}
    

提交回复
热议问题