gpt4 book ai didi

python - 如何分离数组并根据数组中的索引添加它们?

转载 作者:行者123 更新时间:2023-12-01 01:02:11 24 4
gpt4 key购买 nike

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

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

所以我想要的结果是:

员工姓名工资(他们赚多少钱增加每位员工的工作时间

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

(编辑:格式困惑,所以这里是文本的屏幕截图:enter image description here

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)

最佳答案

熟悉 unpacking a list in Python 的概念很有用。 。您可以使用以下代码来解决您的问题:

names = []
hours = []
more_hours = []
with open('empwages.txt') as f:
for line in f:
name, hour, *more_hs = line.split()
names.append(name)
hours.append(hour)
more_hours.append(more_hs)

print(*names, sep=', ')
print(*hours, sep=', ')
print(*[sum(float(q) for q in e) for e in more_hours])

如果您需要所请求的字符串:

names = []
hours = []
more_hours = []
with open('empwages.txt') as f:
for line in f:
name, hour, *more_hs = line.split()
names.append(name)
hours.append(hour)
more_hours.append(more_hs)

print(more_hours)

names = ', '.join(names)
hours = ', '.join(hours)
more_hours = ', '.join(str(s) for s in [sum(float(q) for q in e) for e in more_hours])


print(names)
print(hours)
print(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

关于python - 如何分离数组并根据数组中的索引添加它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55697123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com