【问题标题】:Python - converting a list of tuples to a list of stringsPython - 将元组列表转换为字符串列表
【发布时间】:2012-07-27 21:48:18
【问题描述】:

我有一个如下所示的元组列表:

[('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]

将每个标记用空格分隔的最pythonic和最有效的方法是什么:

['this is', 'is the', 'the first', 'first document', 'document .']

【问题讨论】:

  • 我添加了一个避免使用%s的答案,对于3.6+版本,它使用f-string,对于以前的版本,它使用str.format

标签: python


【解决方案1】:

很简单:

[ "%s %s" % x for x in l ]

【讨论】:

  • [("%s "*len(x)%x).strip() for x in l] 如果你不知道每个元组有多长......在这个例子中它是 2......但是如果一个有 3 个条目或一些这将说明这一点
  • @JoranBeasley 不,您只需使用 " ".join 即可。
  • @Julian 是的,你的权利...脑子放屁[" ".join(x) for x in l]
  • @Julian:是的,我同意' '.join 处理得很好。看我的回答。
  • 这仅适用于 2 元组。对于较大的 n,将其扩展到 n 元组是很困难的。 ' '.join(tup) 是最好的方法
【解决方案2】:

使用map()join()

tuple_list = [('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]

string_list = map(' '.join, tuple_list) 

正如inspectorG4dget 所指出的,列表推导式是这样做的最pythonic 方式:

string_list = [' '.join(item) for item in tuple_list]

【讨论】:

    【解决方案3】:

    这样做:

    >>> l=[('this', 'is'), ('is', 'the'), ('the', 'first'), 
    ('first', 'document'), ('document', '.')]
    >>> ['{} {}'.format(x,y) for x,y in l]
    ['this is', 'is the', 'the first', 'first document', 'document .']
    

    如果你的元组是可变长度的(甚至不是),你也可以这样做:

    >>> [('{} '*len(t)).format(*t).strip() for t in [('1',),('1','2'),('1','2','3')]]
    ['1', '1 2', '1 2 3']   #etc
    

    或者,可能是最好的:

    >>> [' '.join(t) for t in [('1',),('1','2'),('1','2','3'),('1','2','3','4')]]
    ['1', '1 2', '1 2 3', '1 2 3 4']
    

    【讨论】:

      【解决方案4】:

      我强烈建议您避免使用%s。从 Python 3.6 开始,添加了 f-strings,因此您可以通过以下方式利用此功能:

      [f'{" ".join(e)}' for e in l]
      

      如果您使用的是以前版本的 Python 3.6,您还可以通过使用 format 函数来避免使用 %s,如下所示:

      print(['{joined}'.format(joined=' '.join(e)) for e in l]) # before Python 3.6
      

      替代方案:

      假设每个元组中有 2 个元素,您可以使用以下内容:

      # Python 3.6+
      [f'{first} {second}' for first, second in l]
      
      # Before Python 3.6
      ['{first} {second}'.format(first=first, second=second) for first, second in l]
      

      【讨论】:

      • [f’{} {}’ for *x in l] 会更好
      • @Orbital,我更新了我的答案。你的建议没有用,但我知道你希望我让答案更通用。
      • 糟糕,抱歉,我无法测试它。我认为它会工作
      【解决方案5】:

      假设列表是:

      你可以使用列表推导+join()

      li = [('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')]
      

      您需要做的就是:

      [' '.join(x) for x in li]
      

      你也可以使用ma​​p() + join()

      list(map(' '.join, li))
      

      结果:

      ['this is', 'is the', 'the first', 'first document', 'document .']
      

      【讨论】:

        猜你喜欢
        • 2014-07-14
        • 2011-03-18
        • 2011-05-16
        • 1970-01-01
        • 1970-01-01
        • 2014-10-18
        • 1970-01-01
        • 2022-11-21
        相关资源
        最近更新 更多