[英]Return all pairs from a list in Python 3.4
此代碼適用於Python 2.7,但不適用於3.4。
import numpy as np
import itertools
a = [[3,7,9],[2,7,5],[6,9,5]]
def all_pairs(a, top=None):
d = collections.Counter()
for sub in a:
if len(a)<2:
continue
sub.sort()
for comb in itertools.combinations(sub,2):
d[comb]+=1
return sorted(np.array([i[0] for i in d.most_common(top)]).tolist())
這是我期望的結果:
[[2, 5], [2, 7], [3, 7], [3, 9], [5, 6], [5, 7], [5, 9], [6, 9], [7, 9]]
但是使用Python 3.4,我得到了這個回溯:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
prev_pairs()
File "", line 102, in all_pairs
sub.sort()
AttributeError: 'map' object has no attribute 'sort'
另外,當我只添加一個元素時,我什么也得不到:
all_pairs([3,7,9])
[]
# Expected to get:
[[3,7],[3,9],[7,9]]
是否有更好的方法來編寫此代碼來解決這兩個問題?
在Python 2中, map()
生成一個list
,其中包含sort()
方法。 在Python 3中, map()
生成一個map
對象,它充當一個惰性生成器,並且沒有方法sort()
。 如果你想對它使用sort()
,你必須首先將該對象傳遞給list()
:
sub = list(sub)
sub.sort()
當然,如果你這樣做,你也可以使用sorted()
,它適用於Python 3 map
對象以及list
對象:
sub = sorted(sub)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.