如何将单词列表列表转换为字符串作为句子?

时间:2018-06-16 23:36:52

标签: python python-3.x python-2.7

我已经尝试过将列表转换为其他问题中的字符串,但输出似乎不是我应该得到的。我有[['This','is','here.'],['Second','sentence','here.']]的输入,我想将其转换为字符串并保存到带有输出的文本文件中:

This is here.
Second sentence here.

我做的是,

list = [['This','is','here.'],['Second','sentence','here.']]
with open(outfile, 'w') as newfile:
    newfile.write(str('\n'.join((str(i) for i in list))))

.txt文件中的输出是:

['This', 'is', 'here.']
['Second', 'sentence', 'here.']

非常感谢帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以尝试lst = '\n'.join(' '.join(i) for i in txt)此外,这很好  使用 list以外的变量名称:

txt = [['This','is','here.'],['Second','sentence','here.']]
with open(outfile, 'w') as newfile:
    lst = '\n'.join(' '.join(i) for i in txt)
    newfile.write(lst)

更新

看起来列表中的项目有None,您可以按照other answer中的说明对其进行过滤,并使用以下内容:

txt = [['This','is','here.'],['Second','sentence','here.'], ['Here',None, 'is']]
lst = '\n'.join(' '.join(list(filter(None.__ne__, i))) for i in txt)
print(lst)

结果:

This is here.
Second sentence here.
Here is

正如下面的评论中所建议的那样,在这种情况下,只需添加其他时间结果即可将filterlist comprehension进行比较,list comprehension更快:

%%timeit
txt = [['This','is','here.'],['Second','sentence','here.'], ['Here',None, 'is']]
lst = '\n'.join(' '.join(list(filter(None.__ne__, i))) for i in txt)

# Result: 100000 loops, best of 3: 4.52 µs per loop
%%timeit
txt = [['This','is','here.'],['Second','sentence','here.'], ['Here',None, 'is']]
lst = '\n'.join(' '.join(([j for j in i if j != None])) for i in txt)

# Result: 100000 loops, best of 3: 3.28 µs per loop

答案 1 :(得分:0)

您可以使用str.join将列表转换为字符串

>>> l=[['This','is','here.'],['Second','sentence','here.']]
>>> print ('\n'.join([' '.join(e) for e in l]))
This is here.
Second sentence here.
>>>