我有一个包含多个列表的列表,我想将这些列表合并为单个字符串,以便可以在其上使用counter()方法。
样本列表
List1= [
['this is the first document',
'this document is the second document'],
['and this is the third one',
'is this the first document']]
需要输出“这是第一个文件,这个文件是第二个文件,这是第三个文件,这是第一个文件”
谢谢。
您可以使用内置的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
使用.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'
创建一个计数器对象,并使用object_name.element()遍历并打印。
c = Counter(List1)
for i in c.elements():
print ( i, end = " ")
有关详细信息,[https://www.geeksforgeeks.org/python-counter-objects-elements/][1]
遍历整个列表并追加到字符串。
类似的东西
l = [['...','..'],['..']...]
result = ''
for sublist in l:
for item in sublist:
result += item
outer_list = [["innerlist1element1", "innerlist1element2"],["innerlist2element1","innerlist2element2"]]
res_string = ""
for innerlist in outer_list:
res_string+= ' '.join(innerlist)+" "
print(res_string)
for循环遍历外部列表中的列表,join()将其所有元素连接在一起,并在两者之间留有空格。但是,要连接结果字符串,将使用良好的旧串联'+'。
用列表理解替换循环:
outer_list = [["innerlist1element1", "innerlist1element2"],["innerlist2element1","innerlist2element2"]]
a = [' '.join(i) for i in outer_list]
print(' '.join(a))
列表理解更快,更易读。在python docs中查看更多。