Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何转换列表?_Python - Fatal编程技术网

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']
    
  • 如何在1中连接转换列表中的每个术语。转换为单个值,每个术语之间有一个空格,如下所示

     ['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']