【问题标题】:how to store values from a .csv file as numbers in a dictionary如何将 .csv 文件中的值存储为字典中的数字
【发布时间】:2015-10-08 23:16:51
【问题描述】:

我有一个 .csv 文件,如下所示:

A,3
B,2
C,5
D,1

我想将上述值存储在以字母为键的字典中。我的代码如下:

reader11 = csv.reader(open('file.csv'))
for row in reader11:
   if row and row[0]:
      excount[row[0]]=[i for i in row[1] if i]
print excount.items()

excount 是:

[('A', ['3']), ('B', ['2']), ('C', ['5']), ('D', ['1'])]

数字以字符串形式存储在excount 中。如何将它们存储为数字(如下所示)?

[('A', [3]), ('B', [2]), (C, [5]), ('D', [1])]

【问题讨论】:

标签: python-2.7


【解决方案1】:

您可以将字符串传递给内置的int() 函数以将其转换为数字。像这样的东西可以工作:

excount[row[0]] = [int(i) for i in row[1] if i]

有关int函数的更多信息,请参阅Python documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2021-05-08
    • 2021-01-12
    相关资源
    最近更新 更多