Search code examples
pythonpython-3.xpandaslistnested-lists

remove parenthesis from a list of lists


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?


Solution

  • 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.