英文:
How can I delete a row from array and then add a new row to dictionary?
问题
我有一个名为teams[]的数组,我从一个csv文件中填充了数据(csv文件包含团队和得分):
```python
teams = []
with open("2018m.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
row["rating"] = int(row["rating"])
teams.append(row)
然后我有一个名为counts{}的字典,我想要通过模拟来统计每支球队赢得冠军的次数。问题是,我想要将teams[]中的所有球队添加到counts{}中,然后给它们一个值0(因为起初没有任何冠军),所以它会看起来像这样:
counts = {
"Brasil": 0,
"Argentina": 0,
"France": 0
}
我需要知道如何仅获取来自teams[]的团队行,并同时将其值设置为0。我想通过循环来实现这个,添加teams[i],但我不知道如何仅获取团队行,也不知道如何给它赋值。
帮助,已经卡住一段时间了!
我想象中的代码是:
counts[teams[i]] = 0
但我知道这是不可能的。
<details>
<summary>英文:</summary>
I have an array called teams[] which I filled with data from a csv file (the csv has a team and a score):
teams = []
with open("2018m.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
row["rating"] = int(row["rating"])
teams.append(row)
But then I have a dictionary called counts{} where I want to count how many times a team won the championship by a simulation. The thing is that I want to add all the teams from teams[] and then give them a value 0 (cause at first nobody will have any championship) so it will look kind of like this
counts {
"Brasil": 0,
"Argentina": 0,
"France": 0
}
I need to know how to get only the team row from teams[] and at the same time add it a value of 0. I tought to this with a loop and add teams[i] but I don't know how to just take the team row and also how to give it the value.
HELP BEEN STUCK FOR A WHILE!!
I imagine something like:
counts[teams[i]] = 0
but i Know it is not possible
</details>
# 答案1
**得分**: 0
使用字典推导式:
```python
counts = {team['team']: 0 for team in teams}
英文:
Use a dict comprehension:
counts = {team['team'] : 0 for team in teams}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论