该代码在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
对象,该对象充当惰性生成器并且不具有method sort()
。如果要sort()
在其上使用,则必须先将该对象传递给list()
:
sub = list(sub)
sub.sort()
当然,如果您这样做的话,不妨使用sorted()
,它可以在Python 3map
对象以及以下list
对象上使用:
sub = sorted(sub)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句