-4

Say I have a list like the one below.

['butter', 'potatos', 'cheese', ['butter', 'potatos'], ['butter', 'cheese'], ['potatos', 'cheese']]
  1. How can I change the list to one below where the two words combinations becomes one word?

    ['butter', 'potatos', 'cheese', 'butter+potatos', 'butter+cheese', 'potatos+cheese']
    
  2. How can I concatenate each of the term in the transformed list in 1. into a single value with a space between each of the term as below?

     ['butter potatos cheese butter+potatos butter+cheese potatos+cheese']
    
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • Possible duplicate of [Flattening a shallow list in Python](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) – Prune Feb 23 '16 at 23:17

2 Answers2

3

Something like this maybe:

>>> food = ['butter', 'potatos', 'cheese', ['butter', 'potatos'], ['butter', 'cheese'], ['potatos', 'cheese']]
>>> combinations = [f if type(f) != list else '+'.join(f) for f in food]
>>> combinations
['butter', 'potatos', 'cheese', 'butter+potatos', 'butter+cheese', 'potatos+cheese']
>>> output = ' '.join(combinations)
>>> output
'butter potatos cheese butter+potatos butter+cheese potatos+cheese'

The combinations is assigned the value of a list comprehension. The comprehension will go through all the values, called f, in food and check if the item is a list or not. If it's a list, the strings in the list will be joined together, otherwise f will be used as-is.

For the output, the join method is used again.

André Laszlo
  • 15,169
  • 3
  • 63
  • 81
0
>>> say = ['butter', 'potatos', 'cheese', ['butter', 'potatos'], ['butter', 'cheese'], ['potatos', 'cheese']]

>>> # 1
>>> ['+'.join(x) if isinstance(x, list) else x for x in say]
['butter', 'potatos', 'cheese', 'butter+potatos', 'butter+cheese', 'potatos+cheese']
>>> # 2
>>> [' '.join([x if isinstance(x, str) else '+'.join(x) for x in say])]
['butter potatos cheese butter+potatos butter+cheese potatos+cheese']
Aziz Alto
  • 19,057
  • 5
  • 77
  • 60