简体   繁体   English

在Python列表中找到最小的数字

[英]finding smallest number in list for python

I am trying to use a for loop to get an average for each week and for the month in python: 我正在尝试使用for循环来获取python中每周和每月的平均值:

sum = 0
sumA = 0
sumB = 0
sumC = 0
sumD = 0

week1 = (35,38,30,34,27,40,39)
week2 = (35,38,30,34,27,40,39)
week3 = (35,38,30,34,27,40,39)
week4 = (35,38,30,34,27,40,39)

for x in (week1):
    sum = sum + week1[x]
    avg1 = (sum + week1[x]) / 7
for y in (week2):
    sumA = sumA + week2[y]
    avg2 = (sumA + week2[y]) / 7
for z in (week3):
    sumB = sumB + week3[z]
    avg3 = (sumB + week3[z]) / 7
for k in (week4):
    sumC = sumC + week4[k]
    avg4 = (sumC + week4[k]) / 7

sumD = sum + sumA + sumB + sumC
avg = (sum + sumA + sumB + sumC) / 28

that is it but its not correct. 就是这样,但这是不正确的。 can i get some help please 我可以帮忙吗

Assuming you are using Python 2.x, the / operator for two integers uses integer divsion, ie the result of the division is rounded down to the next integer. 假设您使用的是Python 2.x,则两个整数的/运算符使用整数除法,即除法的结果四舍五入为下一个整数。 Try it in the interactive interpreter: 在交互式解释器中尝试:

>>> 5/3
1

To get the correct floating point division, either use 要获得正确的浮点除法,可以使用

from __future__ import division

or convert one of the operands to float first 或将其中一个操作数转换为float

avg = float(sum + sumA + sumB + sumC) / 28

You don't need these loops. 您不需要这些循环。 Here's a quick example: 这是一个简单的示例:

>>> week1 = (35,38,30,34,27,40,39)
>>> average1 = sum(week1) / len(week1)
>>> average1
34

As in the comments: 如评论中所示:

The above example (in Python 2.x) needs one part cast to float if you want 'true' division (eg 34.71). 上面的示例(在Python 2.x中)如果需要“真”除法(例如34.71),则需要将一部分强制转换为浮点数。

In Python 3.x the single / division defaults to 'true' division so the above snippet would be correct (although with a different resulting value for average1 ). 在Python 3.x中单/除法默认为“真”分裂所以上面的片段将是正确的(尽管具有用于不同结果值average1 )。

There are several problems here. 这里有几个问题。 First, for x in lst yields the elements of lst , not the indices. 首先, for x in lst产生元素lst ,而不是索引。 Second, you add in the elements twice, once when updating sum , then again when updating avg . 其次,将元素添加两次,一次是在更新sum ,一次是在更新avg Just compute avg outside the list. 只需计算列表之外的avg Third, divide by a float instead of an int to prevent truncation: 第三,用float代替int来防止截断:

for x in (week1):
    sum = sum + x
avg1 = sum / 7.
list = [....]
avg = sum(list)/float(len(list))

>>> def ave(numbers):
...  return sum(numbers) / len(numbers)
... 
>>> week1 = (35,38,30,34,27,40,39)
>>> week2 = (35,38,30,34,27,40,39)
>>> week3 = (35,38,30,34,27,40,39)
>>> week4 = (35,38,30,34,27,40,39)
>>> ave(week1)
34
>>> ave(week1+week2+week3+week4)
34
>>>


As others pointed out, use from __future__ import division if you want a non-truncated result 正如其他人指出的那样,如果您想要不被截断的结果,请使用from __future__ import division

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

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