How do I replace the values in a list with nested lists? For example:
array1 = [[1,2],[3,4],[5,6,7,8]]
array2 = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]
With these arrays, I need to replace all the values of array1 with the values of array2. The final array will look like the following:
final_array = [[0.1,0.2],[0.3,0.4],[0.5,0.6,0.7,0.8]]
As you said you wanted to replace array1
sublists values by the values of array2
, this will do what you want:
array1 = [[1, 2], [3, 4], [5, 6, 7, 8]]
array2 = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
it = iter(array2)
array1 = [[next(it) for _ in sublist] for sublist in array1]
This works because the length of array2
matches the sum of array1
sublists lengths and you kind of use use array1
as a template of list of sublists with various lenghts.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments