Home > Software engineering >  Insert in list comprehension
Insert in list comprehension

Time:04-25

I have two lists, both containing numpy arrays of the same dimensions.

To simplify, a and b are here represented as ints and strings:

a = [0, 1, 2, 3]

b = ['a', 'b', 'c']

I would like to insert a value for b in a, at each position from 1, and return a list of numpy arrays. Like this:

[array(['0', 'a', '2', '3'], dtype='<U21'),
 array(['0', '1', 'b', '3'], dtype='<U21'),
 array(['0', '1', '2', 'c'], dtype='<U21')]

It needs to be scalable since the length of a and b are always unknown, and a always has an extra object at index 0.

Any ideas?

CodePudding user response:

a = [1,2,3]
b = ["a","b","c"]

ls = []
for i,k in enumerate(b):
    c = a[:]
    c.insert(i 1,k)
    ls.append(c)

this will fill ls with the lists you need.

CodePudding user response:

this can be solved with a normal for-loop:

import numpy as np
a = [0, 1, 2, 3]
b = ['a', 'b', 'c']

l = []

#for dealing with the extra object we start iterating from 1
for i in range(0,3):
    a = [0, 1, 2, 3]   #we keep 'a' or a copy of the original list
    a[i 1] = b[i]      #we assign a 'b' value in 'a'
    l.append(np.asarray(a))  #we save it and go to the next position
    
print(l)

Output:

[array(['0', 'a', '2', '3'], dtype='<U21'),
 array(['0', '1', 'b', '3'], dtype='<U21'),
 array(['0', '1', '2', 'c'], dtype='<U21')]

It's not a good practice assigning a statement in a list comprehension so it's recommended to use for-loops, you can get more examples on this post: use python list comprehension to update dictionary value

Output: [1]: https://i.stack.imgur.com/jx160.png

CodePudding user response:

You could try:

a = [0, 1, 2, 3]
b = ['a', 'b', 'c']

arr = np.tile(np.array(a, dtype='str'), (len(a) - 1, 1))
idx = np.arange(len(arr)   1)
arr[idx[:-1], idx[1:]] = b
result = list(arr)

Result:

[array(['0', 'a', '2', '3'], dtype='<U1'),
 array(['0', '1', 'b', '3'], dtype='<U1'),
 array(['0', '1', '2', 'c'], dtype='<U1')]
  • Related