簡體   English   中英

以所有可能的方式增加每個列表元素

[英]Increase each list element in all possible ways

我有一個列表: test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

需要使用Python 標准庫以所有可能的方式增加每個列表元素。 這是一個難題,我已經這樣做了:

test = [elem + 1 for elem in test]

for i in range(len(test)): test[i] += 1

test = map(lambda x : x + 1, test)

test = [sum(elem) for elem in zip(test, [1]*len(test))]

還有其他想法嗎?

你可以使用遞歸,(你可以使用TrueFalse而不是10 ,但那只是瘋狂的談話):

def recurseadd(test):
    if test:
        return [test[False] + True] + recurseadd(test[True:])
    else:
        return test

而不是+你可以使用[test[0] + 1].extend(recurseadd(test[1:]))

如果需要,您可以使用operator.add而不是+ ,使用functools.partialitertools.imap

from functools import partial
from operator import add
from itertools import imap

addone = partial(add, 1)

test = list(imap(addone, test))  # don't really use imap if you want a list

您可以使用itertoolsiziprepeat

test = [sum(elem) for elem in izip(test, repeat(1))]

sum的另一種方法,靈感來自 Eren 對 GWW 回答的評論:

test = sum(([x+1] for x in test), [])

你可以使用xrange而不是range ,你可以使用itertools.count(1).next()生成1 s ...

有無數的小變化,但你的三個加上遞歸版本似乎涵蓋了基本的。 艾倫的簡化版也不錯。

In [23]: import operator

In [24]: import itertools

In [25]: list(itertools.starmap(operator.add,zip(test,itertools.repeat(1))))
Out[25]: [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]

In [26]: list(itertools.imap(operator.add,test,itertools.repeat(1)))
Out[26]: [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]

In [30]: list(itertools.starmap(operator.add,itertools.izip_longest(test,[],fillvalue=1)))
Out[30]: [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]

我想到了兩個使用 python 的 reduce function,但是,它們與您已經完成的類似。

>>> [reduce(lambda x,y: x + y, l) for l in zip(li, [1]*len(li))]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
>>> [reduce(lambda x,y: x + y, (z,1)) for z in li]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM