简体   繁体   English

将字符串值转换为列表python

[英]Convert string values to list python

I'm trying to figure out an easy way to take a string in a line from a file that is being read using readline(). 我试图找出一种简单的方法来从正在使用readline()读取的文件中的一行中提取字符串。 Specifically, there are multiple integer values which is where I am running into issues: 具体来说,我遇到了多个整数值:

10 20 30 

I would like the values above to be converted into a list of separate integers: 我希望将上面的值转换为单独的整数列表:

[10, 20, 30] 

The values would then be summed within a separate class. 然后将这些值汇总到一个单独的类中。 I'm certain there is something simple I could do here, but I'm just drawing a blank. 我敢肯定,我可以在这里做些简单的事情,但我只是在画一个空白。 Thanks in advance! 提前致谢!

Here's more context as to what I am trying to do. 关于我要做什么的更多信息。 I'm passing the integers into an updateMany method in my class: 我将整数传递给类中的updateMany方法:

vals = infile.readline() 
a.updateMany(int(vals.split())

updateMany() takes the list and sums them, adding them to a list variable local to the class. updateMany()获取列表并对其求和,然后将它们添加到该类本地的列表变量中。

例如:

thelist = [int(s) for s in thestring.split()]

You could use: 您可以使用:

x = [int(i) for i in "10 20 30".split()]

then 然后

sum(x)

You van use map() . 您可以使用map() It takes items from a list and applies given function upon them. 它从列表中获取项目并对其应用给定功能。

>>> string = "10 20 30"
>>> map(int, string.split())
[10, 20, 30]

If you just use space as separator, you can use split method of a string object: 如果仅使用空格作为分隔符,则可以使用字符串对象的split方法:

>>> num_line = '10 20 30'
>>> [int(num) for num in num_line.split() if num]
[10, 20, 30]

If your separator is more than one char like ',' and '.' 如果分隔符是多个字符,例如','和'。 or space, you can use re.split(): 或空格,您可以使用re.split():

>>> import re
>>> re_str = "[,. ]"
>>> num_line = '10, 20, 30.'
>>> [int(num) for num in re.split(re_str, num_line) if num]
[10, 20, 30]

Thanks everyone for your help and different ways of solving this. 感谢大家的帮助以及解决此问题的不同方法。 I ended up using the following to get my values: 我最终使用以下方法来获取自己的价值观:

intList = [int(i) for i in vals.split(sep=' ')]
a.updateMany(intList)

Cheers! 干杯!

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

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