Home > OS >  Facing issues in create new list from string item with brackets and percentages
Facing issues in create new list from string item with brackets and percentages

Time:11-21

I have one array that showed in x:

x=['T','0(99%)','2','0','8(56%)','0','0','0']

I want to get as:

target=[0,2,0,8,0,0,0]

How to extract numbers from such group of values and also how can it do with many lists in a loop?

CodePudding user response:

x = ['T','0(99%)','2','0','8(56%)','0','0','0']
output = [item[0] for item in x if item[0].isdigit()]

output is: ['0', '2', '0', '8', '0', '0', '0']

doing it in a loop:

out_list_of_lists = []
for x in list_of_lists:
    out_list_of_lists.append([item[0] for item in x if item[0].isdigit()])

you can even do a nested list comprehension if that's your thing:

out_list_of_lists = [[item[0] for item in x if item[0].isdigit()] for x in list_of_lists]
  • Related