jimhub
jimhub

Reputation: 53

Slice a list within a list?

I am trying to slice a list in python so that I get two separate lists: one with the keys, and one with the values. My list looks like this:

[(b'a', 2), (b'surprise,', 1), (b'but', 1), (b'welcome', 1), (b'one', 1), (b'for', 1), (b'sure.', 1)]

I am relatively new at coding and so I am just wondering how I would be able to do something like that.

Upvotes: 1

Views: 84

Answers (4)

Netwave
Netwave

Reputation: 42678

Use zip unpacking the data:

>>> l = [(b'a', 2), (b'surprise,', 1), (b'but', 1), (b'welcome', 1), (b'one', 1), (b'for', 1), (b'sure.', 1)]
>>> [*zip(*l)] # similar to list(zip(*l))
[(b'a', b'surprise,', b'but', b'welcome', b'one', b'for', b'sure.'), (2, 1, 1, 1, 1, 1, 1)]

If you want lists instead of tuples, use a comprehension:

>>> [list(x) for x in zip(*l)]
[[b'a', b'surprise,', b'but', b'welcome', b'one', b'for', b'sure.'], [2, 1, 1, 1, 1, 1, 1]]

For fixing if l is an empty list you can use combiantion with an or expresion:

>>> keys, values = [*zip(*[])] or ([], [])
>>> keys
[]
>>> values
[]

Upvotes: 4

Mad Physicist
Mad Physicist

Reputation: 114230

Since you specifically use the terms "keys" and "values", you can do it via a dictionary:

my_dict = dict(my_list)
my_keys = list(my_dict.keys())
my_values = list(my_dict.values())

If all you care about is some kind of (read only) iterable, don't bother wrapping in list.

Upvotes: 2

Zik
Zik

Reputation: 302

Use map:

l = [(b'a', 2), (b'surprise,', 1), (b'but', 1), (b'welcome', 1), (b'one', 1), (b'for', 1), (b'sure.', 1)]
l1, l2 = map(lambda x: x[0], l), map(lambda x: x[1], l)
print('l1 is: {}\nl2 is: {}'.format(list(l1), list(l2)))

Upvotes: 0

gahooa
gahooa

Reputation: 137272

Netwave has a very correct answer, but here is a straightforward way to do it:

Given that:

data = [(b'a', 2), (b'surprise,', 1), (b'but', 1), (b'welcome', 1), (b'one', 1), (b'for', 1), (b'sure.', 1)]

You can use a loop to unpack it:

keylist = []
vallist = []

for item in data:
  keylist.append(item[0])
  vallist.append(item[1])

# You end up with keys in keylist and values in vallist

You can also use "tuple unpacking" to put each tuple into two vars:

keylist = []
vallist = []

for k,v in data:
  keylist.append(k)
  vallist.append(v)

# You end up with keys in keylist and values in vallist

You can streamline with list comprehensions:

keylist = [item[0] for item in data]
vallist = [item[1] for item in data]

Just to be obnoxious, you can use tuple unpacking as well:

kl,vl = [item[0] for item in data], [item[1] for item in data]

Upvotes: 3

Related Questions