[英]More elegant/pythonic way of unpacking a list?
有没有更优雅/ Python化的方法来解压缩此列表?
feature_set = [['flew'], ['homes'], ['fly home']]
变成这个:
flew|homes|fly home
没有这个丑陋的代码:
output = ''
for feature in feature_set:
if len(feature) < 2: output += ''.join(feature) + '|'
if len(feature) > 1: output += ' '.join(feature) + '|'
print(output[:-1])
使用chain.from_iterable
展平列表,然后使用str.join
例如:
from itertools import chain
feature_set = [['flew'], ['homes'], ['fly home']]
print("|".join(chain.from_iterable(feature_set)))
输出:
flew|homes|fly home
我希望你想要这样的东西。
'|'.join([inList[0] for inList in feature_set])
第一join
通过每个内部列表的每个元素map
,然后join
用于再次map
结果
"|".join(map(lambda x: " ".join(x), feature_set))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.