QuantumTraveler
QuantumTraveler

Reputation: 271

Return all pairs from a list in Python 3.4

This code works in Python 2.7, but not in 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())

This is the result I expect:

[[2, 5], [2, 7], [3, 7], [3, 9], [5, 6], [5, 7], [5, 9], [6, 9], [7, 9]]

But using Python 3.4, I get this traceback:

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'

Also, when I add just one element, I get nothing:

all_pairs([3,7,9])
[]

# Expected to get:
[[3,7],[3,9],[7,9]]

Is there a better way to write this code to solve both of these issues?

Upvotes: 3

Views: 229

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49318

In Python 2, map() produces a list, which has the method sort(). In Python 3, map() produces a map object, which acts as a lazy generator and does not have the method sort(). If you want to use sort() on it, you'll have to pass that object to list() first:

sub = list(sub)
sub.sort()

Of course, if you're doing that, you might as well just use sorted(), which works on Python 3 map objects as well as list objects:

sub = sorted(sub)

Upvotes: 3

Related Questions