简体   繁体   English

将字符串列表转换为 int

[英]Convert list of strings to int

I have a list of strings that I want to convert to int, or have in int from the start.我有一个字符串列表,我想将其转换为 int,或者从一开始就包含在 int 中。

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)

Which gives me a list like [['5382', '1399', '3534'], ['1908', '8123', '2857'] .这给了我一个列表,如[['5382', '1399', '3534'], ['1908', '8123', '2857'] I tried map(int,... and one other thing, but I get errors such as:我试过map(int,...和另一件事,但我收到错误,例如:

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

You can use a list comprehension:您可以使用列表理解:

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

or map或地图

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

or just change your line或者只是改变你的线路

lst.append(z)

to

lst.append(map(int, z))

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.您的地图不起作用的原因是您尝试将int应用于列表列表的每个列表,而不是每个子列表的每个元素。

update for Python3 users: Python3 用户的更新

In Python3, map will return a map object which you have to cast back to a list manually, ie list(map(int, z)) instead of map(int, z) .在 Python3 中, map将返回一个 map 对象,您必须手动将其转换回列表,即list(map(int, z))而不是map(int, z)

You can read the whole input and use a regular expression:您可以读取整个输入并使用正则表达式:

import sys
import re

numbers = map(int, re.findall(r'\d+', sys.stdin.read()))
print numbers, sum(numbers)

On input输入时

11 22
33

The output is输出是

[11, 22, 33] 66

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM