0

I know this has already been asked in other thread but I recall a neater way of doing this:

so here is a code that i know how to unpack things:

list = [[1, "tom"], [4, "jane"], [2, "peter"], [5.5, "Ursala"]]
points=[p for p, n in list]
name=[n for p, n in list]

So I know this is how I extract lists from list of list

but i remember there is some neater way of doing this. It's something like.

points,name = list

it gives me however the error: too many values to unpack (expected 2)

is this method for dictionary? not applicable for list of list?

Wiley Ng
  • 307
  • 3
  • 14

1 Answers1

3

Using zip you get tuples, convert those tuples to list using map

* is used for unpacking the iterable

l = [[1, "tom"], [4, "jane"], [2, "peter"], [5.5, "Ursala"]]
points,name = map(list, zip(*l))
# just to point out numpy is not only for numbers
import numpy as np
l = [[1, "tom"], [4, "jane"], [2, "peter"], [5.5, "Ursala"]]
ln = np.array(l)
points, name = ln[:, 0], ln[:, 1]

PS: list is already reserved by python use some other unreserved name

eroot163pi
  • 1,791
  • 1
  • 11
  • 23