猿问

如何使用 Python 从同一个文本文件中分离不同的输入格式

我是编程和 python 的新手,我正在寻找一种方法来区分同一输入文件文本文件中的两种输入格式。例如,假设我有一个像这样的输入文件,其中的值以逗号分隔:

5
华盛顿,A,10
纽约,B,20
西雅图,C,30
波士顿,B,20
亚特兰大,D,50
2
纽约,5
波士顿,10

其中格式为NN行 Data1,MM行 Data2。我尝试打开文件,逐行读取并将其存储到一个列表中,但我不确定如何为 Data1 和 Data2 生成 2 个列表,这样我会得到:

Data1 = ["Washington,A,10", "New York,B,20", "Seattle,C,30", "Boston,B,20", "Atlanta,D,50"]
Data2 = ["纽约,5", "波士顿,10"]

我最初的想法是遍历列表,直到找到整数i,从列表中删除整数并继续进行下一次i迭代,同时将后续值存储在单独的列表中,直到找到下一个整数,然后重复。但是,这会破坏我的初始列表。有没有更好的方法来分隔不同列表中的两种数据格式?


莫回无
浏览 213回答 3
3回答

婷婷同学_

你绝对是在正确的轨道上。如果您想在此处保留原始列表,则实际上不必删除整数i;你可以继续下一个项目。代码:originalData = []formattedData = []with open("data.txt", "r") as f :&nbsp; &nbsp; f = list(f)&nbsp; &nbsp; originalData = f&nbsp; &nbsp; i = 0&nbsp; &nbsp; while i < len(f): # Iterate through every line&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; n = int(f[i]) # See if line can be cast to an integer&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; originalData[i] = n # Change string to int in original&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; formattedData.append([])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for j in range(n):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i += 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; item = f[i].replace('\n', '')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; originalData[i] = item # Remove newline char in original&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; formattedData[-1].append(item)&nbsp; &nbsp; &nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("File has incorrect format")&nbsp; &nbsp; &nbsp; &nbsp; i += 1print(originalData)print(formattedData)
随时随地看视频慕课网APP

相关分类

Python
我要回答