如何在python中循环并制作数组对象?

时间:2019-04-20 04:29:32

标签: python arrays json python-3.x

我想像这样制作数组对象:

{'book1':3, 'book2':4, 'book3':5}

来自这样的数组

['book1', 'book1', 'book1', 'book2', 'book2', 'book2', 
'book2', 'book3', 'book3', 'book3', 'book3', 'book3']

该怎么做?我的想法是循环,但不知道要计数相同的值

*对不起,不好解释

4 个答案:

答案 0 :(得分:2)

collections.Counter是完成此任务的便捷内置工具:

from collections import Counter

lst = ['book1', 'book1', 'book1', 'book2', 'book2', 'book2', 'book2', 'book3', 'book3', 'book3', 'book3', 'book3']
print(dict(Counter(lst)))

输出:

{'book1': 3, 'book2': 4, 'book3': 5}

答案 1 :(得分:0)

您可以执行以下操作:

arr = ['book1', 'book1', 'book1', 'book2', 'book2', 'book2', 'book2', 'book3', 'book3', 'book3', 'book3', 'book3']

final = {}

# loop through each item in the array
# if it is NOT found in the dictionary, put it
# in the dictionary and give it a count of 1
# if it IS found in the dictionary, increment its value
for x in arr:
    if x in final:
        final[x] += 1
    else:
        final[x] = 1

print(final)

答案 2 :(得分:0)

您也可以使用collections.Counter,它正是针对这种情况而设计的。

from collections import Counter

li =['book1', 'book1', 'book1', 'book2', 'book2', 'book2', 'book2', 'book3', 'book3', 'book3', 'book3', 'book3']
print(dict(Counter(li)))
#{'book1': 3, 'book2': 4, 'book3': 5}

答案 3 :(得分:-2)

listA=['book1', 'book1', 'book1', 'book2', 'book2', 'book2', 'book2', 'book3', 'book3', 'book3', 'book3', 'book3']
dictA={}
for x in listA:
    if x in dictA.keys():
        dictA[x]+=1
    else:
        dictA[x]=1