Code Monkey
Code Monkey

Reputation: 844

More elegant/pythonic way of unpacking a list?

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

Answers (3)

Hooting
Hooting

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

Devendra Bhat
Devendra Bhat

Reputation: 1219

I hope you want something like this.

'|'.join([inList[0] for inList in feature_set])

Upvotes: 0

Rakesh
Rakesh

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

Related Questions