此代码适用于 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
对象以及 列出
对象:
sub = sorted(sub)
关于python - 从 Python 3.4 的列表中返回所有对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34056288/