Home > Back-end >  Replace 1d list as a column of a 2d list
Replace 1d list as a column of a 2d list

Time:01-26

pt_list = [3, 4, 32, 20, 20, 10, 10, 13, 30, 10]

pt = 0

points = [
    ['1.', pt],
    ['2.', pt],
    ['3.', pt],
    ['4.', pt],
    ['5.', pt],
    ['6.', pt],
    ['7.', pt],
    ['8.', pt],
    ['9.', pt],
    ['10.', pt]
]

for i in range(0,10,1):
    for j in points:
        points[i][1] = j

I tried some different ways and I can't find anything on the internet for this specific example. I would like to have the pt_list inside of each pt, so the first one would be ['1.', 3] the second one ['2.', 4] and the third one ['3.'32'] and so on.

How can I achieve this?

CodePudding user response:

You can use zip, which allows you to iterate the two lists in tandem, taking the 0-th column from each row of the 2d list points:

points = [[x[0], y] for x, y in zip(points, pt_list)]

The nested loop you've attempted won't be effective for this sort of problem (that approach would give you a Cartesian Product of the two lists -- for each element of list 1, pair it with each element from list 2), but you can fix your code as follows:

for i in range(len(points)):
    points[i][1] = pt_list[i]

Note that I've used len(points) rather than the hardcoded 10.

These solutions assume your lists are the same length.

CodePudding user response:

You can try this syntax to initialize this particular 2D list:

ls = [[str(i 1) '.',pt_list[i]] for i in range(0,10)]

This is known as list comprehension, and it basically means that we are generating i lists where i is in range from 0 to 10, and that each element would be:

[str(i 1) '.',pt_list[i]]

You can also understand this by manuallly substituting values of i from 0..10 and see what values it gives.

You can also change the value 10 with len(pt_list)..

  •  Tags:  
  • Related