Search code examples
pythonstringlistnested

Pythonic Way to Sum List of Lists of Strings


I've found a way to do what I want which is, But I'm wondering if there's a way I can get this down to one line.

I have a list of list of lists of strings, as compared to a lists of numbers (for which there's an answer: [Sum of list of lists; returns sum list)

Example List:

list = [['T=-40F A=0K', 'T=-15F A=0K', 'T=59F A=0K', 'T=98F A=0K', 'T=120F A=0K'],
 ['T=-40F A=10K','T=-15F A=10K','T=59F A=10K','T=98F A=10K','T=120F A=10K']]

Example Output:

['T=-40F A=0K', 'T=-15F A=0K', 'T=59F A=0K', 'T=98F A=0K', 'T=120F A=0K', 'T=-40F A=10K', 'T=-15F A=10K', 'T=59F A=10K', 'T=98F A=10K', 'T=120F A=10K']

I can join these with this method:

new = []
for i in [['T=%.0fF A=%.0fK'%(t,a)for t in TEMP] for a in ALT]:
    new = new + i

Anyone got anything?

As for the application im adding a legend to a matplotlib plot

This would be really easy, and an awesome feature with sum(list)


Solution

  • Using List Comprehension:

    >>> my_list = [['T=-40F A=0K', 'T=-15F A=0K', 'T=59F A=0K', 'T=98F A=0K', 'T=120F A=0K'], ['T=-40F A=10K','T=-15F A=10K','T=59F A=10K','T=98F A=10K','T=120F A=10K']]
    >>>
    >>> [y for x in my_list for y in x]
    ['T=-40F A=0K', 'T=-15F A=0K', 'T=59F A=0K', 'T=98F A=0K', 'T=120F A=0K', 'T=-40F A=10K', 'T=-15F A=10K', 'T=59F A=10K', 'T=98F A=10K', 'T=120F A=10K']
    

    And you should not use list as your variable name.