2014-03-12 44 views
3

添加元素可以說我有一個元組像下面:在一個元組

s = 15, 50, 71, 4, 19 

,我試圖在元組逐一互相元素添加每個元素。即找到15和50,15和71等的總和...

所以我試圖搞砸地圖功能,但我從來沒有使用過它,但我已經拿出這個,但我得到TypeError:map()的參數2必須支持迭代錯誤。

test1 = tuple(map(operator.add, s[0], s[1])) 

我也試圖讓每個元素的整數,但我也得到一個錯誤

test1 = tuple(map(operator.add, int(s[0]), int(s[1]))) 

我希望另一種方法有人知道我能做到什麼,我試圖做的。

謝謝!

編輯:

謝謝大家,所有的建議都是有益的,我發現了一些不同的方式做什麼,我需要做!

+1

你期望的輸出成爲你的榜樣? – interjay

+0

和你有沒有關心,如果有重複? –

+0

爲了最終結果,可以說我正在尋找2的數字等於65的總和,所以我試圖找出哪兩個數字的組合將等於那個數字 – Neemaximo

回答

5

我想也許你正在尋找itertools.combinationsitertools.starmap

In [7]: s = 15, 50, 71, 4, 19 

In [8]: import itertools as IT 

In [9]: import operator 

In [10]: list(IT.starmap(operator.add, (IT.combinations(s, 2)))) 
Out[10]: [65, 86, 19, 34, 121, 54, 69, 75, 90, 23] 

IT.combinations(s, 2)返回從s與所有對項目的迭代器:

In [11]: list(IT.combinations(s, 2)) 
Out[11]: 
[(15, 50), 
(15, 71), 
(15, 4), 
(15, 19), 
(50, 71), 
(50, 4), 
(50, 19), 
(71, 4), 
(71, 19), 
(4, 19)] 

IT.starmap適用operator.add每個對。如果希望參數解壓縮,則使用starmap而不是mapoperator.add需要2個參數,而這個對只是一個單一的對象 - 一個2元組。因此,我們使用starmap將2元組解包爲2個參數,然後將它們傳遞給operator.add

+0

謝謝,這就是我一直在尋找的! – Neemaximo

0

這是我做過的最粗糙的事情。 不需要輸入任何東西雖然

>>> s = 15, 50, 71, 4, 19 
>>> s 
(15, 50, 71, 4, 19) 
>>> x = [a + s[i-1] for a in s[i:] for i in range(1,len(s)) for a in s[i:]] 
>>> x 
[65, 86, 19, 34, 121, 54, 69, 75, 90, 23] 
3

這似乎簡單,只需使用sum ...

starmap(operator.add ...)是一回事map(sum ...)

tuple(map(sum, itertools.combinations(s, 2))) 
Out[9]: (65, 86, 19, 34, 121, 54, 69, 75, 90, 23) 
0

我通常用列表解析法的地圖......你更喜歡哪一個,似乎是風格化的。該方法是這樣的:

tuple(x+y for x,y in combinations(s, 2)) 

它也比地圖快一些,但我不是100%確定爲什麼。

1

如果你不想使用combinations() -

s = 15, 50, 71, 4, 19 
l = len(s) 
print [s[i] + s[j] for i in xrange(l - 1) for j in xrange(i + 1, l)] 

# [65, 86, 19, 34, 121, 54, 69, 75, 90, 23]