【问题标题】:How do I convert a list of strings to a list of ints inside a dictionary?如何将字符串列表转换为字典中的整数列表?
【发布时间】:2020-01-26 00:01:44
【问题描述】:

所以我正在将 CSV 文件中的数据写入 Python,这样我就可以用它来做一些数学运算。 CSV文件中的数据是模拟学生成绩;所以一个学生的名字,然后是5个考试成绩。我正在使用以下代码将所有数据放入字典中:

csvfile = open('Lab03-testdata.csv', newline='')
linesreader = csv.reader(csvfile, delimiter=';')

testScores = {}

for l in linesreader:
    testScores[l[0]] = l[1:]

这可行,但每个键都有一个对应的 strings 列表,而不是整数。我的输出看起来像:

'John Doe': ['100', '55', '34', '22', '99']

为了进行任何数学运算,我不得不使用 for 循环将我想要的测试分数添加到单独的列表中,并在执行此操作时将分数转换为整数。但是我希望字典中的所有数据都已经是整数。我想要更像这样的东西:

'John Doe': [100, 55, 34, 22, 99]

那么如何将值列表转换为整数?

【问题讨论】:

  • list(map(int, l[1:]))

标签: python string list dictionary int


【解决方案1】:

在此代码中添加 int(...) 强制转换:

for l in linesreader:
    testScores[l[0]] = l[1:]

注意 for 循环中的变化:

for l in linesreader:
    testScores[l[0]] = [int(i) for i in l[1:]]

【讨论】:

  • 谢谢!这是否在功能上使用单行 for 循环将行中的每个测试分数转换为 int,然后再将其添加到列表中?
  • 这正是它的作用。它被称为列表理解。 list(map(int, l[1:])) 做的几乎一样
【解决方案2】:

你必须将你的数据从 str 转换为 int

for l in linesreader:
    testScores[l[0]] = list(map(int, l[1:]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2019-07-31
    • 2022-12-18
    相关资源
    最近更新 更多