简体   繁体   中英

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:

[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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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