How to append tuples from for loop to list

Viewed 139
inter = []

for inter in intersections:

    a, b = inter
    for i in range(6):
        for j in range(6):
            lines_edges[int(b) + i, int(a) + j] = [0, 0, 255]
            cv2.circle(lines_edges,(int(a),int(b)), 5, (0, 255, 0), cv2.FILLED)


print(inter)

OUTPUT:

(255.49047141424273, 253.22266800401204)
(261.42908992416034, 227.0)
(312.7111046847889, 227.0)
(361.3178929765886, 296.4939799331104)
(362.0041891809848, 227.5)
(362.5263157894737, 165.73684210526315)
(410.92892156862746, 228.5)
(463.1585111920874, 228.5)

OUTPUT I WANT:

[(255.49047141424273, 253.22266800401204) (261.42908992416034, 227.0) (312.7111046847889, 227.0) (361.3178929765886, 296.4939799331104) (362.0041891809848, 227.5) (362.5263157894737, 165.73684210526315) (410.92892156862746, 228.5) (463.1585111920874, 228.5)]
3 Answers

You just need to:

  1. Prepare the empty array for result
  2. Append the tuple to the array by using append()

For example:

result = []
tuples = [(1,2), (3,4)]
for tuple in tuples:
    result.append(tuple)

Or if you want to construct tuples from operations like you want the list have tuples containing the min and max for each input tuple, you can do:

result = []
tuples = [(3,1,7,2), (3,4,2,1)]
for tuple in tuples:
    inner_tuple = (min(tuple), max(tuple))
    result.append(inner_tuple)

I used the list of tuples above just as reference, the thing you only need is the use of .append() in the for loop.

You need to change the variable name to contain the result, because when you set the variable inter to be the inner element of the intersections, the inter will be no longer an empty array, so you need to change it:

# Change inter to result
result = [] 
for inter in intersections:
    # do things here...
    item = .....
    result.append(item)

print(result)

You just have to append tuple in inter list in loop only.

inter.append(tuple)
s = []
for inter in intersections:

    a, b = inter

    for i in range(6):
        for j in range(6):

            lines_edges[int(b) + i, int(a) + j] = [0, 0, 255]
            cv2.circle(lines_edges,(int(a),int(b)), 5, (0, 255, 0), cv2.FILLED)


    s.append(inter)
a = [(int(x), int(y)) for x,y in s]
print(a)
Related