删除数组中的一行,然后将新行添加到字典中如何做?

huangapple go评论62阅读模式
英文:

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[&quot;rating&quot;] = int(row[&quot;rating&quot;])
        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&#39;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[&#39;team&#39;] : 0 for team in teams}

huangapple
  • 本文由 发表于 2023年2月24日 12:35:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552676.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定