0

Here is a list a=[1,1,1,2,4,2,4,32,1,4,35,23,24,23]

I do this in python:

unique_number=list(set(a))
ans=map(lambda x:a.index(x),unique_number)

output:

<map at 0x2b98b307828>

I want to know what's wrong with my code and find an more efficient way to achieve this.

Garvey
  • 1,197
  • 3
  • 13
  • 26
  • 2
    What if you `print(list(ans))` ? – khelwood Aug 29 '17 at 08:27
  • @khelwood It returns `[7, 0, 3, 10, 4, 11, 12]` – Garvey Aug 29 '17 at 08:30
  • What exactly is your desired output? Also you don't need lambda to get `list(map(a.index,list(set(a))))` – Chris_Rands Aug 29 '17 at 08:31
  • 2
    Possible duplicate of https://stackoverflow.com/q/1303347/2301450 – vaultah Aug 29 '17 at 08:32
  • 1
    If you are trying to get the indexes of the unique values, then @khelwood is right, hence the output. If you are trying to get the Unique value itself, then remove `ans=map(lambda x:a.index(x),unique_number)` and directly print `unique_number` – SajidSalim Aug 29 '17 at 08:33
  • Possible duplicate of [Handling map function in python2 & python3](https://stackoverflow.com/questions/41090310/handling-map-function-in-python2-python3) – Netwave Aug 29 '17 at 08:36

3 Answers3

2

This code would work as you expected in Python 2. In Python 3, map returns an iterator. You could, e.g., convert it to a list:

>>> ans=map(lambda x:a.index(x),unique_number)
>>> list(ans)
[7, 0, 3, 10, 4, 11, 12]
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Try this:

for value in map(lambda x:a.index(x),unique_number):
     print(value)

or append this:

for var in ans:
     print(var)
matsbauer
  • 424
  • 3
  • 16
1

You can avoid keep re-indexing and building a set first - simply build a dict iterating over a backwards as the dictionary will only keep the last value for a key (in this case - the earliest appearing index), eg:

a=[1,1,1,2,4,2,4,32,1,4,35,23,24,23]

first_index = {v:len(a) - k for k,v in enumerate(reversed(a), 1)}
# {1: 0, 2: 3, 4: 4, 23: 11, 24: 12, 32: 7, 35: 10}

This way you're only scanning the sequence once.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280