简体   繁体   中英

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])

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

我希望你想要这样的东西。

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

第一join通过每个内部列表的每个元素map ,然后join用于再次map结果

"|".join(map(lambda x: " ".join(x), feature_set))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM