繁体   English   中英

如何从基于3个列表的特定索引输出输出(所有3个列表在相同位置上)

[英]How do I print out an output from a specific index based upon 3 Lists (same position on list for all 3)

我正在尝试创建一个程序,其中有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]: 枚举可迭代,start = 0

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


def name_index(name_list, search_name):
    for index, item in enumerate(name_list):
        if item == search_name:
            return index
    return -1


emp_name = input("gimmie name: ")

idx = name_index(names, emp_name)
if idx == -1:
    print("Name {:s} not found".format(emp_name))
else:
    wage = float(wages[idx])
    hour = hours[idx]        
    print("{:s} worked {:.2f} hours at $ {:.2f} per hour earning $ {:.2f} ".format(names[idx], hour, wage, wage * hour))

如果向量的长度相同,则可使用range

for i in range(0,len(name),1):
    payOut = float(wage[i]) * float(hours[i])
    product = (name[i], wage[i], payOut)
    print(product)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM