首页 > 解决方案 > 如何分隔数组并根据它们在数组中的索引添加它们?

问题描述

我正在尝试制作一个工资计算器,用户在其中插入一个 .txt 文件,程序会计算工作小时数。

到目前为止,我能够将姓名、工资值和小时数分开,但我不知道如何将小时数加在一起。

所以我想要的结果是:

员工姓名 工资(他们赚了多少 每名员工的工作时数

这是数据集(txt的文件名是-> empwages.txt):

(编辑:格式混乱,所以这里是文本的屏幕截图:在此处输入图像描述

Spencer 12.75   8   8   8   8   10
Ruiz    18  8   8   9.5 8   8
Weiss   14.80   7   5   8   8   10
Choi    15  4   7   5   3.3 2.2
Miller  18  6.5 9   1   4   1
Barnes  15  7.5 9   4   0   2

期望的结果:

'Spencer', 'Ruiz', 'Weiss', 'Choi', 'Miller', 'Barnes'
'12.75', '18', '14.80', '15', '18', '15'
'42', '41.5', ... and so on

当前代码:

infile = open("empwages.txt","r")
masterList = infile.readlines()

nameList = []
hourList = []
plushourList = []
for master in masterList:
    nameList.append(master.split()[0])
    hourList.append(master.split()[1])
    x = 2
    while x <= 6:
        plushourList.append(master.split()[x])
        x += 1


print(nameList)
print(hourList)
print(plushourList)

标签: pythonarrayspython-3.x

解决方案


尝试使用zip

with open("empwages.txt") as f:
    lines = [line.split() for line in f]
    names, hours, *more_hours = zip(*lines)
    print(names)
    print(hours)
    print([sum(map(float, i)) for i in zip(*more_hours)])

('Spencer', 'Ruiz', 'Weiss', 'Choi', 'Miller', 'Barnes')
('12.75', '18', '14.80', '15', '18', '15')
[42.0, 41.5, 38.0, 21.5, 21.5, 22.5]

这会:

  • 按行拆分文件,并按单词拆分行
  • 将每行的第一个单词放入names,第二个放入hours,其余放入 more_hours

*_您可以根据需要在 之前添加更多变量。

(编辑为正确总结小时数)。


推荐阅读