关键是通过每一个项目,如果在列表中的项目的索引你循环甚至您添加到col1
否则添加到col2
这将与任意数量的空格分隔的项目工作
import re
with open("test.txt") as f:
inputString = f.read()
#remove all extra spaces so all items separated by only one space
inputString = re.sub(r" +", " ", inputString)
itemsInString = inputString.split(" ")
col1 = []
col2 = []
for index, item in enumerate(itemsInString):
if index % 2 == 0:
col1.append(float(item))
else:
col2.append(float(item))
print(col1)
print(col2)
这给你以下几点:
COL1 = [234.45, 667.4556, 332.333, 554.2564]
COL2 = [234.3455, 566.3311, 564.322, 21.203]
写回了一个文件:
writeString = ""
for item in zip(col1, col2):
writeString += str(item[0]) + " " + str(item[1]) + "\n"
with open("outfile.txt", "w") as f:
f.write(writeString)
这里还有一个更优化的方式来写,而不字符串连接到文件但它不太清楚
with open("outfile.txt", "w") as f:
f.write("\n".join(([" ".join([str(a[0]), str(a[1])]) for a in zip(col1, col2)])))
从你的第一个项目到第二个项目你有两个空格,所有其他的都有一个空格。这是你的实际文件格式还是只是一个错字? – Keatinge