【问题标题】: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

【问题讨论】:

  • 所以你需要一个元组列表?
  • share您尝试过的代码并喜欢反馈。

标签: 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

【讨论】:

  • 这是否回答了您的问题,如果是,请接受。谢谢!
猜你喜欢
  • 1970-01-01
  • 2010-10-19
  • 1970-01-01
  • 2011-12-12
  • 2015-07-12
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多