如何在Python循环中执行迭代的元素总和

时间:2015-07-09 13:43:42

标签: python for-loop sum iteration mean

我是Python的新手,我在理解其逻辑运作方面遇到了麻烦。 我试图构建一个简单的代码,给定两个列表,找到每个列表之间的差异,并返回最小差异的平均值。

我们说我有这两个清单:

list1=[1, 4, 10]
list2=[2, 3, 6]

使用下面的代码,我可以使用第二个数字迭代第一个列表的数字:

for x in list1:

   diff=[abs(y-x) for y in list2]
   print (diff)

[1, 2, 5] # that is, 1-2, 1-3 and 1-6
[2, 1, 2] # that is, 4-2, 4-3 and 4-6
[8, 7, 4] # that is, 10-2, 10-3, 10-6

使用以下代码,我可以找到每次迭代的最小差异:

for x in list1:

   diff=[abs(y-x) for y in list2]
   mindiff=min(int(s) for s in diff)

   print (mindiff)

1 
1 
4 

我对此很好。现在我想总结所有最小差异,并将总和除以我计算的差异数。这是我不能得到的部分。 换句话说,我如何构建一个函数来总结for循环所做的所有迭代?在那之后,(在这种情况下,这将是6(1 + 1 + 4))我可以很容易地将list2的最大范围的差异之和除。

我该怎么做?

提前感谢您的回答

3 个答案:

答案 0 :(得分:2)

list1=[1, 4, 10]
list2=[2, 3, 6]

sumOfMinDiffs = 0 # Initialize the sum value to start out at zero

for x in list1:

   diff=[abs(y-x) for y in list2]
   mindiff=min(int(s) for s in diff)
   print (mindiff)

   sumOfMinDiffs += mindiff # Keep track of the sum


maximumRangeOfList2 = max(list2) - min(list2) # I think this is what you mean by "maximum range of list 2"

print(sumOfMinDiffs/maximumRangeOfList2) # Tah dah, this is your answer
# print(sumOfMinDiffs/len(list2)) # This is your answer if you just want to divide by the length of list2

上述代码旨在执行以下操作:

  • 将一个sum变量保存在循环之外,并在每个循环中递增它
  • 在for循环结束时,计算列表2"的最大范围是什么?将并存储在变量
  • 您的最终答案只是将sum变量除以范围变量

答案 1 :(得分:2)

我认为你可以通过for循环外的变量实现你想要的,添加每次迭代的值和一个计算迭代次数的变量。

list1=[1, 4, 10]
list2=[2, 3, 6]


min_sum = 0
n = 0
for x in list1:

    diff=[abs(y-x) for y in list2]
    mindiff=min(int(s) for s in diff)
    min_sum += mindiff
    n+=1

    print (mindiff)

print(min_sum/n)

希望有所帮助

答案 2 :(得分:1)

以下代码可能会帮助您解决问题。

list1=[1, 4, 10]
list2=[2, 3, 6]

n = len(list2)
sum_min = 0

for x in list1:

    diff=[abs(y-x) for y in list2]
    mindiff=min(int(s) for s in diff)

    sum_min += mindiff  # iterating will keep on adding min of differences 1 + 1 + 4

    print (mindiff)

print(sum_min/n)  # mean minimum difference

我认为,为了计算列表的最小差异的平均值,您需要将最小差异的总和除以每组中的差异数(即list2的长度)。 如果你想修改代码,我想你已经明白了如何去做。