2

我创建了一个函数,它接受一个整数列表并从左到右减去以返回最终答案。我不热衷于使用计数变量来跳过第一个循环,因为这似乎很浪费 - 在 Python 中有更好的方法吗?

def subtract(numlist):
''' numlist -> int
    Takes a list of numbers and subtracts from left to right
'''
answer = numlist[0]
count = 0
for n in numlist:

    if count != 0:
        answer -= n

    count += 1
return answer

print(subtract([10,2,4,1]))
4

5 回答 5

2

只需将除第一个元素之外的所有内容相加,然后减去:

>>> def subtract(numlist):
...    return numlist[0] - sum(numlist[1:])
...
>>> print(subtract([10,2,4,1]))
3
于 2013-07-14T00:34:16.490 回答
1

您可以使用列表切片:

>>> def subtract(numlist):
...     result = numlist[0]
...     for n in numlist[1:]:
...             result -= n
...     return result
... 
>>> subtract(L)
3

正如您所展示的,我们首先获取列表中的第一个元素,但是我们可以将第一个元素切掉并照常迭代,而不是使用计数器遍历整个列表。

于 2013-07-14T00:32:41.110 回答
1

此特定操作内置于 python2 中,可functools在 python3 中使用,如下所示reduce

reduce(...)
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

因此:

>>> l = [10, 2, 4, 1]
>>> import operator
>>> reduce(operator.sub, l)
3
于 2013-07-14T00:58:59.800 回答
0

您可以获取列表的迭代器并使用它来循环它:

def subtract(l):
    it = iter(l)
    first = next(it)

    # Since the iterator has advanced past the first element,
    # sum(it) is the sum of the remaining elements
    return first - sum(it)

它比使用切片快一点,因为您不必复制列表。

于 2013-07-14T00:34:50.787 回答
0

而不是使用计数变量,您可以尝试for n in numlist[1:]

更多关于列表切片

于 2013-07-14T00:33:41.270 回答