Python 如何转换列表?
假设我有一个类似下面的列表Python 如何转换列表?,python,Python,假设我有一个类似下面的列表 ['butter', 'potatos', 'cheese', ['butter', 'potatos'], ['butter', 'cheese'], ['potatos', 'cheese']] 如何将列表更改为下面的列表,其中两个单词组合变成一个单词 ['butter', 'potatos', 'cheese', 'butter+potatos', 'butter+cheese', 'potatos+cheese'] 如何在1中连接转换列表中的每个术语。转
['butter', 'potatos', 'cheese', ['butter', 'potatos'], ['butter', 'cheese'], ['potatos', 'cheese']]
['butter', 'potatos', 'cheese', 'butter+potatos', 'butter+cheese', 'potatos+cheese']
['butter potatos cheese butter+potatos butter+cheese potatos+cheese']
可能是这样的:
>>> 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'
组合
被分配列表的值。理解过程将遍历food
中名为f
的所有值,并检查项目是否为列表。如果是列表,则列表中的字符串将连接在一起,否则将按原样使用f
对于输出,再次使用了join
方法。这就是为什么我只有你一半的代表。@TimCastelijns:)忍者编辑。它现在与另一个几乎相同,只是你的缺少解释可能重复
>>> 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']