![](/img/trans.png)
[英]Python : compare lists of a list by length and create new lists of equal sizes
[英]Python map on not equal length lists
簡而言之,我曾經做過這樣的事情,知道它不會崩潰:
[3]> (mapcar #'+ '(1 2 3) '(1 2))
(2 4)
python中的等效項似乎崩潰了:
>>> map(lambda x,y : x + y, [1,2,3], [1,2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
python中是否有一個功能類似於不等長列表上的lisp版本? 還是有辦法改變地圖的行為?
此問題適用於Python 2.x(感謝@ user2357112)。 Python 3.x中的map
文檔說:
當最短的可迭代輸入耗盡時,迭代器將停止。
因此,在Python 3.x中,您可以只使用map
:
In [1]: list(map(lambda a, b: a + b, [1, 2, 3], [1, 2]))
Out[1]: [2, 4]
但是Python 2.x中的map
文檔說:
如果一個可迭代項比另一個可迭代項短,則假定它使用None項目擴展。
因此,您首先應該zip
以下列表:
In [2]: map(sum, zip([1, 2, 3], [1, 2]))
Out[2]: [2, 4]
因為zip
會將截斷的列表截斷為最短參數序列的長度(如文檔中所述)
您還可以定義自己的函數zip_with
( 此答案的示例 ):
import itertools
def zip_with(f, *coll):
return itertools.starmap(f, itertools.izip(*coll))
用法示例:
In [3]: list(zip_with(operator.add, [1, 2, 3], [1, 2]))
Out[3]: [2, 4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.