如何在python中把一个列表组合成字符串?

问题描述 投票:0回答:5

我有一个包含多个列表的列表,我想把这些列表合并成一个单一的字符串,这样我就可以使用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
5个回答
1
投票

你可以使用内置的 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

0
投票

使用.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'

0
投票

创建一个计数器对象,并使用object_name.element()对其进行迭代,然后打印。

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

更多信息 [https:/www.geeksforgeeks.orgpython-counter-objects-elements][1]


0
投票

迭代整个列表并追加到一个字符串。

类似于

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

0
投票
outer_list = [["innerlist1element1", "innerlist1element2"],["innerlist2element1","innerlist2element2"]]
res_string = ""
for innerlist in outer_list:
    res_string+= ' '.join(innerlist)+" "
print(res_string)

for循环在外层列表中遍历列表,join()将所有元素连接起来,中间有一个空格。然而,为了连接结果的字符串,我们使用了老式的连接法'+'。

用list comprehension代替for loop。

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

列表理解的速度更快,更易读。蟒蛇文档 更多。

© www.soinside.com 2019 - 2024. All rights reserved.