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

标签 python arrays python-3.x

我正在尝试制作一个工资计算器,用户插入一个 .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/

相关文章:

python - 将 x 轴绘制为日期

python - 使用 python 在 linux 上运行 phantomjs

c# - 将十六进制字符串转换为图像

python - 自定义权重初始化 tensorflow tf.layers.dense

Python pygame - 中心轴旋转线段

python - 使用 Python 解决编程竞赛

python - 为什么 pytest 总是说 "ImportError: attempted relative import with no known parent package"

Javascript 算法在 1's and 0' s 矩阵中查找最大尺寸正方形

php - 给定 Y 数字,得到 X 数字的每种组合?

python-3.x - Python 类型提示填充了 myclass 对象的双端队列