如何在python中将数字除以任意数组中的每个元素?



对Python来说非常陌生,我试图为我的经理做一个小费计算器。

计算小费的方式是服务器工作一天中的百分比,他们得到该百分比的小费。例如,如果服务器 1 在当天工作 30% 的小时数,则他们会收到当天给出的提示的 30%。

我试图弄清楚如何将一个数字(代码中的变量"hourNum"(除以存储服务器工作时间的数组中的每个元素。这将使我获得服务器工作一天的百分比。

使用下面的代码,数学似乎没有正确计算或正确打印。

不幸的是,我一直无法在堆栈溢出上找到任何类似的问题,可以提出相同的问题。

下面附的是源代码,问题出在标题为"计算服务器工作日百分比"的最后一节中:

#get hours in the day
print('Enter how many hours were worked in the day: ')
hourNum = int(input())
#get tips for the day
print("Enter how much tips were earned (enter to the nearest whole dollar, do not use a dollar sign): ")
tipNum = int(input())

# creating an empty list 
lst = [] 

# number of elemetns as input 
serverNum = int(input("Enter number of servers that worked the day : ")) 

# iterating till the range 
print("Enter the number of hours each server worked (in order): ")
for i in range(0, serverNum): 
ele = int(input()) 

lst.append(ele) # adding the element 

print("You entered: ", lst) 

#calculate percent of day servers worked
n = 0
for i in range (0,serverNum):
print (hourNum / lst[0 + n])
n+1

任何提示或帮助将不胜感激:)

表达式hourNum / lst[i]100 * lst[i] / hourNum,以便此值表示每个服务器在工作日 (hourNum( 中工作的小时数百分比乘以 100,使其成为百分比。此外,与其打印最终的百分比,为什么不将它们存储在列表中,以便程序记住它们?

#get hours in the day
hourNum = int(input('Enter how many hours were worked in the day: '))
#get tips for the day
tipNum = int(input("Enter how much tips were earned (enter to the nearest whole dollar, do not use a dollar sign): "))
# creating an empty list 
lst = [] 
# number of elemetns as input 
serverNum = int(input("Enter number of servers that worked the day: ")) 

# iterating till the range 
print("Enter the number of hours each server worked (in order): ")
for i in range(0, serverNum): 
ele = int(input()) 

lst.append(ele) # adding the element 

print("You entered:", lst) 

#calculate percent of day servers worked
lst_percents = []
for i in range (0,serverNum):
lst_percents.append(round(100* lst[i] / hourNum))
print("The percent of day the servers worked:", lst_percents)
<小时 />

示例输入和输出:

Enter how many hours were worked in the day: 10
Enter how much tips were earned (enter to the nearest whole dollar, do not use a dollar sign): 100
Enter number of servers that worked the day: 4
Enter the number of hours each server worked (in order): 
1
2
4
5
You entered: [1, 2, 4, 5]
The percent of day the servers worked: [10, 20, 40, 50]

我将把每个服务器的提示计算留给您。希望使用服务器工作百分比的列表会更容易。

将最后一个代码块更改为以下内容:

#calculate percent of day servers worked
for i in lst:
print(f"Worker {i+1}: {round(i/sum(lst)*100)}%")

最新更新