Home > database >  Convert data structure in Python
Convert data structure in Python

Time:04-05

The data I have look like this:

A=[a,b,c,...,n]
B=[x,y,z,...,n]

I would like to convert this data to following:

C=[((a, x), 1),((b, y), 1),((c, z), 1),...,((n, n), 1)]

a,b,c,x,y,z are all integers

Is it possible to do so?

CodePudding user response:

Assuming lengths are equal I would do it following way

A = [1,2,3]
B = [101,102,103]
C = [((a,b),1) for a,b in zip(A,B)]
print(C)

output

[((1, 101), 1), ((2, 102), 1), ((3, 103), 1)]

CodePudding user response:

If the 1 is only a constant :

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

c = [(x,1) for x in zip(a,b)]

c
[((0, 10), 1),
 ((1, 11), 1),
 ((2, 12), 1),
 ((3, 13), 1),
 ((4, 14), 1),
 ((5, 15), 1),
 ((6, 16), 1),
 ((7, 17), 1),
 ((8, 18), 1),
 ((9, 19), 1)]

CodePudding user response:

There are multiple ways to achieve this and there are other examples here which are correct. I'd like to add one more which uses the itertools package (if you find this interesting, I highly recommend reading the docs).

from itertools import repeat

A = [1,2,3]
B = [101,102,103]
C = list(zip(zip(A, B), repeat(1)))
print(C)

The repeat() function from the itertools package will infinitely repeat the supplied value. Since the zip() builtin function will only zip for the shortest length of either utterable, this will repeat 1 for the length of A or B, whichever is shortest (or if they're the same length).

Output

[((1, 101), 1), ((2, 102), 1), ((3, 103), 1)]

If you don't need this to be a list, but can rather let it be a generator, you can make this code less verbose.

C = zip(zip(A, B), repeat(1))
  • Related