5

I have a numerical list which looks like ['3,2,4', '21,211,43', '33,90,87'] I guess at this point the elements are considered as strings.

I want to remove the inverted comas and to make a list which with all these numbers.

Expected output is [3,2,4, 21,211,43, 33,90,87]

Also, I would like to know if the type of element is converted from to string to integer.

Somebody please help me!

1
  • 3
    [int(x) for string in data for x in string.split(',')] Commented Nov 17, 2020 at 22:58

3 Answers 3

3

What about the following:

result = []
# iterate the string array
for part in ['3,2,4', '21,211,43', '33,90,87']:
    # split each part by , convert to int and extend the final result
    result.extend([int(x) for x in part.split(",")])
print(result)

Output:

$ python3 ~/tmp/so.py 
[3, 2, 4, 21, 211, 43, 33, 90, 87]
Sign up to request clarification or add additional context in comments.

2 Comments

What modifications would you do if the elements contain a character like '-' For example, '2,3,-,5' is an element and you have to eliminate the '-'
@RuaGoa depends on how you want to treat -. If you just skip them, then int(x) for x in part.split(",") if x != "-" should be enough. If you want to make them 0s then you can just use part.replace("-", "0") before splitting. Finally, if you want to convert them to None, I would expand the generator into a second for-loop and use try/except to set to None all the values that were not ints
2

There are 3 moving parts here:

  1. splitting a list of strings
  2. converting a string to integer
  3. flattening a nested list

First one, str.split:

>>> '1,2,3'.split(',')
['1', '2', '3']

Second one int:

>>> int('2')
2

And last but not least, list comprehensions:

>>> list_of_lists = [[1,2],[3,4]]
>>> [element for sublist in list_of_lists for element in sublist]
[1, 2, 3, 4]

Putting all three parts together is left as an exercise for you.

Comments

1
>>> your_list = ['3,2,4', '21,211,43', '33,90,87']      
>>> your_list = [int(num) for item in your_list for num in item.split(",")]
>>> print(your_list)
[3, 2, 4, 21, 211, 43, 33, 90, 87]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.