Diana Mele
Diana Mele

Reputation: 145

Python remove digits from a list and keeps only words and viceversa

I have this list:

my_list = ['11 red', '21 blue', '31 green']

And what I'd like to have is something like this:

list_n = ['11', '21', '31']
list_w = ['red', 'blue', 'green']

Is there a way to save separatly the digits and the words of a list? I've tried this but it doesn't change anything

list_n = [x for x in my_list if not (x.isdigit() or x[0] == '-' and x[1:].isdigit())]

Thank you

Upvotes: 0

Views: 138

Answers (5)

Andreas
Andreas

Reputation: 9207

Don't loop twice over the same list, you can do this instead:

l1, l2 = [], []
for x in (y.split() for y in my_list): l1 += [x[0]]; l2 += [x[1]]

print(l1, l2, sep='\n')
# ['11', '21', '31']
# ['red', 'blue', 'green']

Upvotes: 0

Batuhan Atalay
Batuhan Atalay

Reputation: 148

if you need to check digit part you can use that code below

my_list = ['11 red', '21 blue', '31 green']
list_n = []
list_w = []

for item in my_list:
    for seperate in item.split():
        if seperate.isdigit():
            list_n.append(seperate)
        else:
            list_w.append(seperate)

list_n will be = ['11', '21', '31']

list_w will be = ['red', 'blue', 'green']

Upvotes: 0

S.B
S.B

Reputation: 16564

Try this one, You can do whatever you want in single iteration. No need to iterate two times to fill those to lists:

my_list = ['11 red', '21 blue', '31 green']
list_n = []
list_w = []

for item in my_list:
    n, w = item.split()
    list_n.append(n)
    list_w.append(w)

print(list_n)
print(list_w)

output :

['11', '21', '31']
['red', 'blue', 'green']

Upvotes: 0

Sayse
Sayse

Reputation: 43330

You're overcomplicating it, just split the strings, and take the first and last parts

list_n = [x.split(maxsplit=1)[0] for x in my_list]
list_w = [x.split(maxsplit=1)[-1] for x in my_list]

Upvotes: 2

Tasbiha
Tasbiha

Reputation: 106

You may try using the split method

my_list = ['11 red', '21 blue', "31 green"]
list_n=[]
list_w=[]
for i in my_list:
    x=i.split()
    list_n.append(int(x[0]))
    list_w.append(x[1])

Output when you print these lists:

[11, 21, 31]
['red', 'blue', 'green']

Upvotes: 0

Related Questions