【问题标题】:How to combine a list of lists into string in python如何在python中将列表组合成字符串
【发布时间】:2020-09-30 08:05:45
【问题描述】:

我有一个包含多个列表的列表,我想将这些列表组合成一个字符串,这样我就可以使用 counter() 方法了。

示例列表

 List1= [
     ['this is the first document',
     'this document is the second document'],
     ['and this is the third one',
     'is this the first document']]

需要输出 '这是第一个文档,这是第二个文档,这是第三个文档,这是第一个文档'

谢谢。

【问题讨论】:

    标签: python-3.x list counter


    【解决方案1】:
    outer_list = [["innerlist1element1", "innerlist1element2"],["innerlist2element1","innerlist2element2"]]
    res_string = ""
    for innerlist in outer_list:
        res_string+= ' '.join(innerlist)+" "
    print(res_string)
    

    for 循环遍历外部列表中的列表,并且 join() 将其所有元素与中间的空格连接起来。但是,为了连接结果字符串,使用了良好的旧连接“+”。

    用列表理解替换 for 循环:

    outer_list = [["innerlist1element1", "innerlist1element2"],["innerlist2element1","innerlist2element2"]]
    a = [' '.join(i) for i in outer_list]
    print(' '.join(a))
    

    列表推导更快、更易读。 在python docs 中查看更多信息。

    【讨论】:

    • 虽然这段代码可能会解决问题,但一个好的答案还应该解释代码的什么以及它如何提供帮助。
    • 虽然此代码可能会解决问题,但 including an explanation 关于如何以及为何解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请edit您的答案以添加解释并说明适用的限制和假设。 From Review
    【解决方案2】:

    遍历整个列表并追加到一个字符串。

    类似的东西

    l = [['...','..'],['..']...]
    result = ''
    for sublist in l:
      for item in sublist:
        result += item
    

    【讨论】:

      【解决方案3】:

      创建一个计数器对象并使用 object_name.element() 遍历它并打印。

        c = Counter(List1) 
        for i in c.elements(): 
             print ( i, end = " ")
      

      了解更多信息 [https://www.geeksforgeeks.org/python-counter-objects-elements/][1]

      【讨论】:

        【解决方案4】:

        可以使用内置的join()函数:

        list = [ 'this is the first document', 'this document is the second document', 'and this is the third one', 'is this the first document']
        print(', '.join(list))
        

        输出:

        this is the first document, this document is the second document, and this is the third one, is this the first document
        

        【讨论】:

          【解决方案5】:

          使用 .join() 方法:

          list1= ['this is the first document', 'this document is the second document', 'and this is the third one', 'is this the first document']
          
          list1_joined = ",".join(list1)
          print(list1_joined)
          
          #Output:
          'this is the first document,this document is the second document,and this is the third one,is this the first document'
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-01-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-01-07
            • 2017-11-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多