python - 如何分隔数组并根据它们在数组中的索引添加它们?
问题描述
我正在尝试制作一个工资计算器,用户在其中插入一个 .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)
解决方案
尝试使用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
*_
您可以根据需要在 之前添加更多变量。
(编辑为正确总结小时数)。
推荐阅读
- spring - 如果所有的bean都可以用@Component注解,那么@ComponentScan注解有什么用?
- python-3.x - 如何使用 freeze_model.pb 文件生成预测?
- python - 当使用 Pandas .groupby 时,为什么使用 .agg 而不是直接使用函数,例如 .sum()
- scala - 在 Scala 中的 Array[String,Int] 的内容中添加类似字符串的 Int
- java - 为什么线程创建的数组返回空指针异常?
- julia - 添加包时如何使用 Julia 规避预编译错误
- html - 身体隐藏在固定导航后面
- excel - Excel If 语句引用另一个工作表
- r - R:对一列数据框的每n行求和
- docker - Docker compose,从 windows 主机连接到容器