繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM