简体   繁体   English

将字符串列表转换为数字列表Python

[英]Convert a list of strings to a list of numbers Python

I am using regular expressions in Python 3 to obtain a list of value: 我在Python 3中使用正则表达式来获取值列表:

lst = ['1.1' , '2.2' , '3.3']

Instead, I want a list of numbers as below: 相反,我想要一个数字列表如下:

lst = [1.1 , 2.2 , 3.3]

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

lst = ['1.1' , '2.2' , '3.3']
lst = [float(x) for x in lst]

I'm using lst here because list is already taken by the builtin list . 我在这里使用lst因为list已经被内置list占用。

Try python's map function. 试试python的map函数。 It takes a function and an iterable and applies the function to each item in the iterable. 它接受一个函数和一个iterable,并将函数应用于iterable中的每个项目。

lst = list(map(float, lst))

The call to list is required in python 3, because the built-in map function returns a special map object as opposed to a list. 在python 3中需要调用list ,因为内置map函数返回一个特殊的map对象而不是list。 I would also recommend not using list as a variable name, as list is a built-in function in python. 我还建议不要使用list作为变量名,因为list是python中的内置函数。

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

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