首页 > 解决方案 > Python:对最喜欢的流派应用进行投票的问题

问题描述

我写了这段代码:

num = int(input())
lst = []
Horror = Romance = Comedy = History = Adventure = Action = []

for i in list(range(num)):
    str = input()
    #lst.append(str)
    word = str.split()
    for i in word[1:]:
        if i == "Horror":
            Horror.append(word[0])
        if i == "Romance":
            Romance.append(word[0])
        if i == "Comedy":
            Comedy.append(word[0])
        if i == "History":
            History.append(word[0])
        if i == "Adventure":
            Adventure.append(word[0])
        if i == "Action":
            Action.append(word[0])
        print(i)

for i in [Horror, Romance, Comedy, History , Adventure , Action]:
    print(len(i))

我的问题是 12 中的所有输出!我想要这个输入:

4
hossein Horror Romance Comedy
mohsen Horror Action Comedy
mina Adventure Action History
sajjad Romance History Action

得到这个输出:

Action : 3
Comedy : 2
History : 2
Horror : 2
Romance : 2
Adventure : 1

帮我!

..................................................... .....................

标签: python

解决方案


这就是问题所在

Horror = Romance = Comedy = History = Adventure = Action = []

您每次都指向同一个数组。

您可以通过以下方式轻松验证:

a = b = []
a.append(1)
print(b) -> prints [1]

c, d = [], []
c.append(1)
print(d) -> prints []

但是,Python 有一个很棒的内置对象,称为字典,在这里非常理想。

from collections import defaultdict

a = defaultdict(list)
a["Action"].append("hossein")
print(len(a["Action"]))

这里我使用defaultdict,它会在没有分配值时自动添加一个新列表。


推荐阅读