将字符串列表转换为int [英] Convert list of strings to int

查看:103
本文介绍了将字符串列表转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要转换为int或从一开始就具有int的字符串的列表.

I have a list of strings that I want to convert to int, or have in int from the start.

任务是从文本中提取数字(并求和).我所做的是这样:

The task is to extract numbers out of a text (and get the sum). What I did was this:

for line in handle:
    line = line.rstrip()
    z = re.findall("\d+",line)
    if len(z)>0:
        lst.append(z)
print (z)

哪个给了我一个像[['5382', '1399', '3534'], ['1908', '8123', '2857']的列表.我尝试了map(int,...和另一件事,但是出现了诸如以下错误:

Which gives me a list like [['5382', '1399', '3534'], ['1908', '8123', '2857']. I tried map(int,... and one other thing, but I get errors such as:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

推荐答案

您可以使用列表理解:

>>> [[int(x) for x in sublist] for sublist in lst]
[[5382, 1399, 3534], [1908, 8123, 2857]]

或地图

>>> [map(int, sublist) for sublist in lst]
[[5382, 1399, 3534], [1908, 8123, 2857]]

或者只是更改您的行

lst.append(z)

lst.append(map(int, z))

您的地图不起作用的原因是您尝试将int应用于列表列表的每个列表,而不是每个子列表的每个元素.

The reason why your map did not work is that you tried to apply int to every list of your list of lists, not to every element of every sublist.

更新:

在Python3中,map将返回一个地图对象,您必须手动将其映射回列表,即list(map(int, z))而不是map(int, z).

In Python3, map will return a map object which you have to cast back to a list manually, i.e. list(map(int, z)) instead of map(int, z).

这篇关于将字符串列表转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆