Home > other >  Combine 2 lists to make a pair of coordinates in a list
Combine 2 lists to make a pair of coordinates in a list

Time:11-19

I need to combine values in two lists(longitude/latitude), to get one combined list (not in tuple or string format) My simple for loop is not iterating correctly over the first list, it is using one value to match all values in the second list, before moving to the next value.

for a in location1:
    for b in location2:
        location3.append(a b)
location3

I am getting this (one 'a' matching to all 'b's first) :

[[41.7770923949, -87.6060037796],
[41.7770923949, -87.6547753762],
[41.7770923949, -87.5716351762],

I want this matching the same sequence in both lists:

[41.7770923949, -87.6060037796],
[41.784575915, -87.6547753762],

Also, trying things with zip/map like this:

list(map(lambda X: (X[0],X[1]), list(zip(location1,location2))))

Gives me this not in the correct form (is there another way?):

[([41.7770923949], [-87.6060037796]),
([41.784575915], [-87.6547753762]),

CodePudding user response:

You need to use zip directly to iterate over the two lists, not with your lambda.

l1 = [ 2, 4, 6, 8 ]
l2 = [ 1, 3, 5, 7 ]

coord = []

for a, b in zip( l1, l2 ):
    coord.append( [ a, b ] )

print( coord )

By the way, your question is related to this one.

CodePudding user response:

You don't need the second for in your code. Try this:

location1 = [[1], [2], [3]]
location2 = [[4], [5], [6]]
location3 = []
for i, _ in enumerate(location1):
    location3.append(location1[i] location2[i])
print(location3)

Result:

[[1, 4], [2, 5], [3, 6]]
  • Related