如何根据 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)


GCT1015
浏览 198回答 3
3回答

倚天杖

您可以简单地使用list.index()列表的方法。无需遍历所有内容。emp_name = input("gimmie name: ") # Weissidx = 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]: enumerate ( iterable, 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 -1emp_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))

qq_遁去的一_1

如果您的向量具有相同的长度,则使用range。for i in range(0,len(name),1):    payOut = float(wage[i]) * float(hours[i])    product = (name[i], wage[i], payOut)    print(product)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python