将包含逗号分隔值的字符串转换为整数

时间:2015-10-30 10:24:18

标签: python string list casting int

给出一个字符串:

>>> string = "0,1,2"
>>> print string
0,1,2

如何拆分字符串并将值转换为整数,将它们放入列表中?

4 个答案:

答案 0 :(得分:1)

只需使用splitint和简单的列表理解。

In [1]: s = "0,1,2"

In [2]: t = s.split(",")

In [3]: t
Out[3]: ['0', '1', '2']

In [4]: v = [int(u) for u in t]

In [5]: v
Out[5]: [0, 1, 2]

一气呵成:

In [7]: v = [int(u) for u in s.split(",")]; v
Out[7]: [0, 1, 2]

答案 1 :(得分:1)

使用split,map and int map通过在给定的可迭代上应用给定的函数(int as now)来生成列表

<强>代码:

string = "0,1,2"
lst = string.split(",")
int_lst  = map(int, lst)
print int_lst

<强>输出:

[0, 1, 2]

答案 2 :(得分:1)

mystring = "0,1,2"
mylist = [int(i) for i in mystring.split(",")]
print mylist

输出:

[1,2,3]

答案 3 :(得分:1)

您可以使用map将广告素材映射到int到您分割时创建的列表的每个元素。

>>> string = "0,1,2"
>>> print map(int, string.split(','))
[0, 1, 2]