【问题标题】:How to convert strings in a text doc into list, and separate list into parts in python如何将文本文档中的字符串转换为列表,并将列表分隔为python中的部分
【发布时间】:2021-01-27 20:29:11
【问题描述】:
我在 .txt 文件中有以下文字,
examplex
exampley
examplea
exampleb
exampleg
exampleh
我想将它们转换成一个列表,然后将列表分成 2 个一组,以便看起来像输出。
输出:
examplex, exampley
examplea, exampleb
exampleg, exampleh
【问题讨论】:
标签:
python
arrays
list
text
format
【解决方案1】:
输入.txt
examplex
exampley
examplea
exampleb
exampleg
exampleh
convert.py
r = open("input.txt", "r")
input = r.read()
output = ""
pair = 0
for i in input:
# Every other '\n' character don't skip a line
if(i == "\n" and pair % 2 == 0):
output += ", "
pair += 1
# increment pair, but still add newline
elif(i == "\n"):
output += i
pair += 1
else:
output += i
r.close()
# Write to output.txt
w = open("output.txt", "w")
w.write(output)
w.close()
输出.txt
examplex, exampley
examplea, exampleb
exampleg, exampleh