【问题标题】:Having trouble with arrays and extracting data from a txt file. (PYTHON 3.8) [closed]数组和从 txt 文件中提取数据时遇到问题。 (Python 3.8)[关闭]
【发布时间】:2020-12-31 02:40:51
【问题描述】:

我在将 txt 文件中的数据导入数组时遇到了一些问题。 这是txt文件中的信息。这是一份员工名单,上面有他们的姓名(不要介意我对《星球大战》的热爱)、每小时工资和工作时间。

Darth Vader
12.50
35
Princess Leia
13.50
40
Han Solo
14.25
10
Luke Skywalker
10.55
55

这是我的代码:

text_file = open("/Applications/Python 3.8/Assignment1.txt", "r")
lines = text_file.readlines()
employees = []
counter = 1
for line in lines:
    print(line)
    employees.append(line[:-1])
    
print(employees)

我如何得到它,所以第一行是一个人的名字,每一秒是他们的工资,每三分之一是他们的工作时间?

【问题讨论】:

  • 不清楚你在问什么。你想让这段代码做什么?请以您想要的格式/结构提供示例输出或数据。
  • 读取一行,用它来设置变量name,读取下一行,将其转换为float,并将其存储为变量wage,读取下一行,转换将其发送至float(或int,如果您只计算整个小时数)并将其存储为hours;然后您可以将元组 (name, wage, hours) 附加到您的 employees 列表中。而不是for line in lines,您可能想要使用while
  • 您所描述的正是您共享的输入文件?你想用代码解决什么问题?

标签: python arrays file


【解决方案1】:

最简单的是这样的:

for line_no in range(0, len(lines), 3):
    name = lines[line_no]
    wage = float(lines[line_no + 1])
    hours = float(lines[line_no + 2])
    employee =  .. merge those into an employee however you want...
    employees.append(employee)

您可能还想查看Stackoverflow answer 以了解其他方式来查看分块列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2021-10-12
    • 2021-10-31
    • 2017-01-08
    相关资源
    最近更新 更多