python - 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
帮我!
..................................................... .....................
解决方案
这就是问题所在
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,它会在没有分配值时自动添加一个新列表。
推荐阅读
- jquery - 使用数据表动态加载数据的分页
- ios - 我有隐藏在父层后面的 calayer (+animation)
- python-3.x - Python 3- 模块
- ios - 有没有办法在 swift 中使用 Mapbox 为标记设置动画或在多边形内循环移动?
- vba - 使用 VBA 在 PowerPoint 中逐步为形状制作动画
- ios - 再次播放 UIViewPropertyAnimator 时出现问题
- angular - Highcharts - 更多系列然后是数据
- javascript - 错误:对象作为 React 子级无效如果您要渲染子级集合,请改用数组。点击注册后
- javascript - 如何在不添加 get 参数的情况下破坏 JavaScript 文件的缓存?
- ruby-on-rails - 显示来自控制器关注的闪光警报