pofi
pofi

Reputation: 11

How to extract a list of integer numbers from a list with strings and integers?

I do have a list which looks like:

a = ['11, 12, 9, 10, 17, 18, 19, \n', '20, 2, 6, 4, 1, 13, 14, 15, \n', '16, 3, 5, 7, 8, 21, 22, 23, \n', '24, 25, 26, 27, 28, 29, 30, 31, \n', '32, 33, 34, 35, 36, 37, 38, 39, \n', '40, 41, 42, 43, 44, 45, 46, 47, \n', '48, 49, 50, 51, 52, 53, 54, 55, \n', '56, \n']

I want to create a list with each integer in it separately with:

a = [int(x) for s in a for x in s.split(',')]

I can see the error because of \n and ' but cant find a solution, which should be looking like:

a = [11, 12, 9, 10, 17, 18, 19, 20, 2, 6, 4, 1, 13, 14, 15, 16, 3, 5, 7, 8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56]

Can someone give some solution in this regard?

Upvotes: 0

Views: 356

Answers (6)

hiro protagonist
hiro protagonist

Reputation: 46869

you could just add if x != ' \n' to your list-comprehension:

a = [int(x) for s in a for x in s.split(',') if x != ' \n']

a more general approach would be this:

b = []
for s in a:
    for x in s.split(','):
        try:
            n = int(x)
        except ValueError:
            continue
        b.append(n)

Upvotes: 1

sahasrara62
sahasrara62

Reputation: 11228

using regex

import re
a = ['11, 12, 9, 10, 17, 18, 19, \n', '20, 2, 6, 4, 1, 13, 14, 15, \n', '16, 3, 5, 7, 8, 21, 22, 23, \n', '24, 25, 26, 27, 28, 29, 30, 31, \n', '32, 33, 34, 35, 36, 37, 38, 39, \n', '40, 41, 42, 43, 44, 45, 46, 47, \n', '48, 49, 50, 51, 52, 53, 54, 55, \n', '56, \n']

a = ','.join(a)
res = [int(i) for i in re.findall(r'[0-9]+', a)]
print(res)
# [11, 12, 9, 10, 17, 18, 19, 20, 2, 6, 4, 1, 13, 14, 15, 16, 3, 5, 7, 8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56]

Upvotes: 0

Shahad Ishraq
Shahad Ishraq

Reputation: 341

You could use String.replace() the remove the \n s.

a = [int(x) for s in a for x in (s.replace(‘, \n’, ‘’)).split(',')]

Upvotes: 0

Reishin
Reishin

Reputation: 1954

One liner and generic solution for python3:

a = [...]
res = [int(x.strip()) for s in a for x in s.split(',') if x.strip().isnumeric()]

Upvotes: 1

Tomerikoo
Tomerikoo

Reputation: 19414

Just strip the unwanted characters:

a = [int(x) for s in a for x in s.strip(', \n').split(',')]

Upvotes: 0

DownloadPizza
DownloadPizza

Reputation: 3466

So to me it looks like you have a list of lines. You could just do:

a = [] # line list
ints = [int(i.strip()) for i in ''.join(list).split(',')]

Or you tell us how you got the line list

Upvotes: 0

Related Questions