[英]How do I print out an output from a specific index based upon 3 Lists (same position on list for all 3)
I am trying to create a program where there are 3 Lists that will print out the name, wage, and total wage based upon their index location on the list. 我正在尝试创建一个程序,其中有3个列表,这些列表将根据列表中的索引位置打印出姓名,工资和总工资。
The length of each variable cannot just be 6, so it should accommodate any input given (name/wage/hour list could as long as desired). 每个变量的长度不能仅为6,因此它应该容纳任何给定的输入(名称/工资/小时列表可以根据需要设置)。 Ignore data validation/formatting as we assume that the user will input the info correctly all the time for all the variables.
忽略数据验证/格式设置,因为我们假设用户将始终为所有变量正确输入信息。
For example, I want my desired output to be (see index 0 in the list of the 3 variables in the code): 例如,我希望得到想要的输出(请参见代码中3个变量的列表中的索引0):
Sanchez worked 42.0 hours at $10.00 per hour, and earned $420.00
$420.00 -> (10.00*42.0) $ 420.00->(10.00 * 42.0)
Currently here is my code: 目前这是我的代码:
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)
You can simply use the list.index()
method for the list. 您可以简单地将
list.index()
方法用于列表。 No need to iterate through everything. 无需遍历所有内容。
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
You could use [Python 3]: enumerate ( iterable, start=0 ) : 您可以使用[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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.