Home > database >  remove parenthesis from a list of lists
remove parenthesis from a list of lists

Time:10-11

I have a list of lists like this:

[[('good weather', 0.6307), ('bad weather', 0.431), ('sunny', 0.4036), ('windy', 0.3692), ('rainy', 0.3663)], [('stay home', 0.5393), ('go outside', 0.5009), ('close windows', 0.4794)]]

I want to remove the parenthesis and the score for every sublist

Expected outcome:

[['good weather','bad weather', 'sunny', 'windy', 'rainy'], ['stay home', 'go outside','close windows']]

Any ideas?

CodePudding user response:

You can do list compression here.

In [1]: [[s for s, f in a] for a in l]
Out[1]: 
[['good weather', 'bad weather', 'sunny', 'windy', 'rainy'],
 ['stay home', 'go outside', 'close windows']]
  • for a in l looping through the main list
  • [s for s, f in a] looping through the sublist and fetching the first element using list comprehension.

CodePudding user response:

I understand that you are trying to replace ('good weather', 0.6307) by its first element:

a = [[('good weather', 0.6307), ('bad weather', 0.431), ('sunny', 0.4036), ('windy', 0.3692), ('rainy', 0.3663)], [('stay home', 0.5393), ('go outside', 0.5009), ('close windows', 0.4794)]]
b = []

for i in a:
    list = []
    for j in i:
        list.append(j[0])
    b.append(list)
print(b)
  • Related