简体   繁体   English

Python 列表:从字符串列表中提取整数

[英]Python list: Extract integers from list of strings

I have a list with the following values, which in fact are strings inside the list:我有一个包含以下值的列表,它们实际上是列表中的字符串:

mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']

How can I extract each value and create a new list with every value inside the list above?如何提取每个值并使用上面列表中的每个值创建一个新列表?

I need a result like:我需要这样的结果:

mylist = [4, 1, 2, 1, 2, 120, 13, 223, 10]

Thank you in advance先感谢您

Just use a list comprehension like so:只需像这样使用列表理解:

mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10']
output = [int(c) for c in ",".join(mylist).split(",")]
print(output)

Output: Output:

[4, 1, 2, 1, 2, 120, 13, 223, 10]

This makes a single string of the values and the separates all of the values into individual strings.这会生成单个值字符串,并将所有值分隔为单独的字符串。 It then can turn them into ints with int() and add it to a new list .然后它可以使用int()将它们转换为整数并将其添加到新list

I'd offer a solution that is verbose but may be easier to understand我会提供一个冗长但可能更容易理解的解决方案

mylist = ['4, 1, 2', '1, 2', '120, 13', '223, 10', '1', '']

separtedList = []
for element in mylist:
    separtedList+=element.split(',')

integerList = []
for element in separtedList:
    try:
        integerList.append(int(element))
    except ValueError:
        pass # our string seems not not be an integer, do nothing

mylist = integerList
print(mylist)

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

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