【问题标题】:Converting File Data to Lists将文件数据转换为列表
【发布时间】:2017-02-24 09:38:28
【问题描述】:

我有一份关于样本员工数据的文件。第一行是姓名,第二行是工资,第三行是人寿保险选举(Y/N),第四行是健康保险选举(PPOI,PPOF,None),如此反复。文件的sn-p如下:

Joffrey Baratheon
190922
Y
PPOI
Gregor Clegane
47226
Y
PPOI
Khal Drogo
133594
N
PPOI
Hodor
162581
Y
PPOF
Cersei Lannister
163985
N
PPOI
Tyrion Lannister
109253
N
PPOF
Jorah Mormont
61078
Y
None
Jon Snow
123222
N
None

如何获取此文件数据并将每种数据类型(姓名、工资、人寿保险、健康保险)提取到四个单独的列表中?
目前,我的代码正在按员工创建一个多维列表,但我最终想要四个单独的列表。我当前的代码如下:

def fileread(text):
    in_file = open(text, "r")
    permlist = []
    x = 1
    templist = []
    for line in in_file:
        line = line.strip()
        templist.append(line)
        if x == 4:
            permlist.append(templist)
            templist = []
            x = 1
        else:
            x+=1
    return (permlist)
def main ():
    EmpData = fileread("EmployeeData.txt")
    index = 0
    print (EmpData[index])

【问题讨论】:

  • 停止破坏这篇文章。内容和答案组成了一个不应再被撕裂的新整体。

标签: python list python-3.x


【解决方案1】:

您可以使用itertools 库中的islice。它将允许您一次迭代 4 行的批次。

from itertools import islice
EmpData = []
headers = ['name', 'salary', 'life insurance', 'health insurance']
record = {}
counter = 1
with open('data.txt', 'r') as infile:
    while counter>0:
        lines_gen = islice(infile, 4)
        counter = 0
        hasLines = False;
        for line in lines_gen:
            record[headers[counter]] = line.strip()
            counter += 1
        EmpData.append(record)
index = 0
print (EmpData[index])

由于有人在这篇文章中抱怨违反学术不诚实行为,我要澄清的是,这是受此 SO 答案启发的生产代码 sn-p 的简化版本:How to read file N lines at a time in Python?

【讨论】:

    【解决方案2】:

    您可以像这样使用 4 个列表推导:

    with open("file.txt",'r') as f:
        lines = f.readlines()
    
    name_list = [lines[i].rstrip() for i in range(0,len(lines),4)]
    salary_list = [lines[i].rstrip() for i in range(1,len(lines),4)]
    life_ins_list = [lines[i].rstrip() for i in range(2,len(lines),4)]
    health_ins_list = [lines[i].rstrip() for i in range(3,len(lines),4)]
    

    【讨论】:

    • 这对我的目的非常有用!我唯一的另一个问题是消除“\ n”字符。要使用 rstrip(),我应该把它放在哪里?当我将其放置为lines=f.readlines().rstrip("\n") 时,我得到一个错误。
    【解决方案3】:

    计算总行数,除以四得到要添加到列表中的人数。

    i = 0
    while i < num_of_people:
        for a in range(0, num_of_people+1):
            namelist.append(i)
            i += 1
            salarylist.append(i)
            i +=1
            ...
    

    像这样拆分数据时要小心。它很容易混淆。 最好将此数据存储到数据库中。

    【讨论】:

      猜你喜欢
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 2012-04-07
      • 1970-01-01
      相关资源
      最近更新 更多