为 CSV 文件中的名称和值列表创建字典

Creating a Dict for the name and a list of the values from a CSV file

我是 python 的初学者,我正试图找出一种方法来从 csv 文件中创建名称字典和值列表。我在网上看到了这段代码。可以用,但是我一点都看不懂。

如有任何帮助,我们将不胜感激。

我感到迷茫的主要领域是 for 循环,然后是 strand = .... 最后 curr_row = row.strip().split(',')]

代码:

strands = []
persons = {}

for ind, row in enumerate(csv_file):
   if ind == 0:
       strand = [strand for strand in row.strip().split(',')][1:]
   else:
       curr_row = row.strip().split(',')
       persons[curr_row[0]] = [int(x) for x in curr_row[1:]]```

the csv file looks like this:
name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5


output : {'Alice': [2, 8, 3], 'Bob': [4, 1, 5], 'Charlie': [3, 2, 5]}


带有枚举的 for 循环将获取 ind 作为行的索引,变量 row 是该行上的数据。

strand 是 csv_file 的第一行,列表理解是 运行 在该行。如果您不确定列表理解是什么,这里有一个 link 解释:https://www.pythonforbeginners.com/basics/list-comprehensions-in-python

row.strip() 函数将删除所有空格。

.split(',') 函数会将 csv_file 中的该行转换为由“,”逗号分隔的项目列表。

因此 strand 将是 ['name'、'AGATC'、'AATG'、'TATC']。

curr_row 正在对以下几行做同样的事情。

所以 csv_file 中的第 2 行是:

爱丽丝,2,8,3

运行宁后,

curr_row = row.strip().split(',')

在第二行,curr_row 将等于 ['Alice', 2, 8, 3]

persons[curr_row[0]] = [int(x) for x in curr_row[1:]]

上面的行使用键 'Alice' 将其添加到字典中,然后使用列表理解循环遍历其余数字,这就是为什么如果您查看列表索引,它会从 1 开始。

curr_row[1:]

如果 link 没有帮助,那么 Corey Schafer 的这个视频可能会帮助我,这就是我学习如何使用列表理解的方式。

https://www.youtube.com/watch?v=3dt4OGnU5sM&t=3s

希望对您有所帮助。