2013-07-14 16 views
1

我創建了一個函數,它接受一個整數列表並從左到右減去以返回最終答案。我不喜歡使用count變量跳過第一個循環,因爲它看起來很浪費 - 在Python中有更好的方法嗎?在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])) 

回答

1

您可以使用列表切片:

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

我們首先得到的第一個元素在列表中,你已經證明,但不是通過整個列表與反迭代,我們可以只需關閉第一個元素並像平常一樣迭代。

+0

謝謝,我很喜歡這個答案! – Phil

+0

@Phil好聽:D – TerryA

0

而不是使用一個計數變量,你可以嘗試for n in numlist[1:]

更多關於list slicing

0

只是總結的一切,但第一要素,然後減去:

>>> def subtract(numlist): 
... return numlist[0] - sum(numlist[1:]) 
... 
>>> print(subtract([10,2,4,1])) 
3 
+0

非常簡單的答案!謝謝。 – Phil

+0

沒問題,歡迎來到SO。不要忘記點擊旁邊的綠色複選標記來標記答案。 – jterrace

0

你可以得到一個iterator列表並使用它來循環它:

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) 

這比使用切片快一點,因爲您不必複製列表。

+0

啊,我從來不知道那個(Iter),謝謝! – Phil

0

這種特殊的操作是建立在以python2,並在python3 functools可用,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 
+0

減少在python 3中被刪除,看起來像OP也在使用python 3 – TerryA

+0

@Haidro:它在python3中的'functools'中:'from functools import reduce' – torek