Python: 列表转整数
我读取了一个文件,并把每一行转换成了一个列表。这个列表的样子大概是这样的:
['15', '2', '0'], ['63', '3', '445', '456', '0'], ['23', '4', '0']
我想从每个列表中提取第一个数字,并把它转换成整数。这样当我使用类型函数的时候,比如:
type(x)
<type 'int'> is returned
另外,当我打印这个变量x的时候,整数是一个一个单独打印出来的,而不是连在一起的。也就是说,如果我从上面的列表中取前三个数字,它们不会打印成:
156323
5 个回答
2
# Converts all items in all lists to integers.
ls = [map(int, x) for x in the_first_list]
或者如果你只想要前两个项目:
ls = [map(int, x[:2]) for x in the_first_list]
在Python 3.x中,你还需要把map包裹在一个列表构造器里,像这样:
ls = [list(map(int, x[:2])) ...
3
如果你想要从每个列表中提取第一个数字,可以用这个方法:[int(L[0]) for L in lines]
(假设你的列表叫做 lines
)。如果你想要每个列表中的前两个数字(从你的问题来看不太好判断),可以用这个:[int(s) for L in lines for s in L[:2]]
;以此类推。
如果你不想要一个包含这些数字的列表,而只是想对它们进行一次操作,可以使用生成器表达式,也就是:
for number in (int(s) for L in lines for s in L[:2]):
...do something with number...
或者可以用类似的嵌套循环方法,比如:
for L in lines:
for s in L[:2]:
number = int(s)
...do something with number...
12
要把你的整数转换成其他类型:
my_ints = [int(l[0]) for l in your_list]
要把它们打印出来:
print "".join(map(str, my_ints))