Reputation: 844
Is there a more elegant/pythonic way of unpacking this list?
feature_set = [['flew'], ['homes'], ['fly home']]
Into this:
flew|homes|fly home
without this ugly code:
output = ''
for feature in feature_set:
if len(feature) < 2: output += ''.join(feature) + '|'
if len(feature) > 1: output += ' '.join(feature) + '|'
print(output[:-1])
Upvotes: 0
Views: 68
Reputation: 1711
first join
each element of each inner list by map
, and then join
again for the map
result
"|".join(map(lambda x: " ".join(x), feature_set))
Upvotes: 0
Reputation: 1219
I hope you want something like this.
'|'.join([inList[0] for inList in feature_set])
Upvotes: 0
Reputation: 82765
Use chain.from_iterable
to flatten list and then use str.join
Ex:
from itertools import chain
feature_set = [['flew'], ['homes'], ['fly home']]
print("|".join(chain.from_iterable(feature_set)))
Output:
flew|homes|fly home
Upvotes: 2