从Python 3.4中的列表返回所有对

时间:2015-12-03 01:27:11

标签: python python-2.7 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]]

有没有更好的方法来编写此代码来解决这两个问题?

1 个答案:

答案 0 :(得分:3)

在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)