gpt4 book ai didi

python - 如何打印出基于 3 个列表的特定索引的输出(所有 3 个在列表中的相同位置)

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:09 24 4
gpt4 key购买 nike

我正在尝试创建一个程序,其中有 3 个列表,这些列表将根据列表中的索引位置打印出姓名、工资和总工资。

每个变量的长度不能只有 6,因此它应该适应任何给定的输入(姓名/工资/小时列表可以根据需要设置)。忽略数据验证/格式设置,因为我们假设用户将始终正确输入所有变量的信息。

例如,我希望我想要的输出是(参见代码中 3 个变量列表中的索引 0):

Sanchez worked 42.0 hours at $10.00 per hour, and earned $420.00

420.00 美元 -> (10.00*42.0)

目前这是我的代码:

name = ['Sanchez', 'Ruiz', 'Weiss', 'Choi', 'Miller', 'Barnes']
wage = ['10.0', '18', '14.80', '15', '18', '15']
hours = [42.0, 41.5, 38.0, 21.5, 21.5, 22.5]


i = 0
for y in name:

payOut = float(wage[i]) * float(hours[i])
product = (name[i], wage[i], payOut)
i += 1
print(product)


empName = input("gimmie name: ") #no data validation neeeded

def target(i,empName):
for x in i:
if x == str(empName):
empName = x #should return index of the empName
'''^^^ this is currently incorrect too as i believe it should return
the index location of the name, which I will use to print out the
final statement based upon the location of each respective variable
list. (not sure if this works)'''



target(name,empName)

最佳答案

您可以简单地使用 list.index()列表的方法。无需遍历所有内容。

emp_name = input("gimmie name: ") # Weiss

idx = name.index(emp_name) # 99% of the work is done right here.

print('{n} worked {h} hours at ${w:.2f} per hour, and earned ${p:.2f}'.format(
n = name[idx],
h = hours[idx],
w = float(wage[idx]), # Convert to float so you can show 2 decimals for currency
p = float(wage[idx]) * hours[idx] # Calculate pay here
))

#Weiss worked 38.0 hours at $14.80 per hour, and earned $562.40

关于python - 如何打印出基于 3 个列表的特定索引的输出(所有 3 个在列表中的相同位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55712133/

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