1

Python: I would like to read set of data

(category, value): (0, 1) (0, 2) (1, 3) (1, 4)

To an array as

[[1, 2],[3, 4]]

Since max number of category is unknown, I would like to create 2D-array dynamically using "append" method.

I wrote a sample code:

data = []
data.append([])

data[0].append(1)
data[0].append(2)

try:
  print (data[1])
except IndexError:
  data.append([])
finally:
  data[1].append(3)
  data[1].append(4)

print(data)

But, I understand that the code is really ugly because I am using "print" to check the access to data[1].

Is there any more beautiful solution for this problem?

Bhargav Rao
  • 41,091
  • 27
  • 112
  • 129
eng27
  • 806
  • 1
  • 8
  • 15

2 Answers2

3

Use itertools.groupby:

import itertools

a = [(0, 1), (0, 2), (1, 3), (1, 4)]
g = itertools.groupby(a, key=lambda x: x[0])
g = [list(i[1]) for i in g]
aviraldg
  • 8,978
  • 6
  • 36
  • 56
1

You can use a list comprehension to do this easily along with a iter.

>>> l = [(0, 1), (0, 2), (1, 3), (1, 4)]
>>> i = iter(l)
>>> [[x[1],y[1]] for x,y in zip(i,i)]
[[1, 2], [3, 4]]

The algorithm here is to iterate over the list of tuples in pairs. This is where iter comes to use. iter creates an iterator that is consumed by the zip function. We then read the tuples into the list comprehension and add only the required two numbers, which is the second indices.

See What does "list comprehension" mean? How does it work and how can I use it? for more details about them.

Community
  • 1
  • 1
Bhargav Rao
  • 41,091
  • 27
  • 112
  • 129
  • Hello sir, I have created room https://chat.stackoverflow.com/rooms/230139/talkwithsir for chat now, I am IST timings in case I slept before you join please forgive me :) – RavinderSingh13 Mar 19 '21 at 18:16