循环列表返回否定索引 [英] Looping Through List Returns Negative Index

查看:122
本文介绍了循环列表返回否定索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决一个列表中的难题,循环遍历每个索引,并将当前索引的左侧和右侧的值相加。如果它发现一个索引,其中左边的值的总和等于右边的值的总和,那么返回该索引。



例如:
[1,2,3,4,3,2,1]
如果我处于索引3(值为4),我们可以看到元素的左右值之和是相等的。
(1 + 2 + 3)=(3 + 2 + 1)。

然而,当输入是一个负值列表时,负指数。这是我的代码:

  def get_equal_sum(list):
for list:
if sum (list [:i])== sum(list [i + 1:]):
print i

list = [1,2,3,4,3,2,1 ]
get_equal_sum(list)
>>> 3

list = [-1,-2,-3,-4,-3,-2,-1]
get_equal_sum(list)
>>> ; -4

为什么它返回-4而不是3?



谢谢!

解决方案

pre $ 对于列表中的$:
如果sum(list [:i])== sum(list [i + 1:]):

i 不是列表的索引, 。事实上,它不会与 IndexError 一起提供负值时切片是因为负面的索引支持python(索引从列表的末尾)只要因为绝对值在范围内(这里是这种情况)。这可能就是为什么你错过了。



如果你想索引你必须使用 enumerate 例如:

  for i,_ in enumerate(l):
如果sum(l [:i])== sum(l [ i + 1:]):

(并且更改 list list 是列表类型)

>

注意 i,_ 表达式来解开索引/值并丢弃这里不需要的值。你也可以去经典:

 对于范围(len(l))中的i:


I'm solving a puzzle that takes in a list, loops through each index and sums the values to the left and to the right of the current index. If it finds an index at which the sum of the values to its left are equal to the sum of the values to its right, then return that index.

For example: [1,2,3,4,3,2,1] If I am at index 3 (value 4), we see that the sum of values of elements to its left and right are equal. (1 + 2 + 3) = (3 + 2 + 1).

However, when the input is a list of negative values, it returns a negative index. This is my code:

def get_equal_sum(list):
    for i in list:
        if sum(list[:i]) == sum(list[i+1:]):
            print i

list = [1,2,3,4,3,2,1]
get_equal_sum(list)
>>> 3

list = [-1,-2,-3,-4,-3,-2,-1]
get_equal_sum(list)
>>> -4

Why is it returning -4 and not 3?

Thank you!

解决方案

When you do

for i in list:
    if sum(list[:i]) == sum(list[i+1:]):

i is not the index of the list but the value. The fact that it doesn't crash with IndexError when you feed the slices with negative values is because negative indexing is supported in python (indexes from the end of the list) as long as absolute value is in range (which is the case here). That's probably why you missed that.

If you want indexes you have to use enumerate for instance:

for i,_ in enumerate(l):
    if sum(l[:i]) == sum(l[i+1:]):

(and change list to l because list is the list type)

Note the i,_ notation to unpack index/value and discard the value which isn't needed here. You could also go with the classical:

for i in range(len(l)):

这篇关于循环列表返回否定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆