How to iterate through a list of tuples in Python?
Solution 1
This print is not exactly as you defined, but you can use this kind of iteration on list of tuples and do whatever you need with each tuple :
coordinates = [(0,0),(0,3),(1,0),(1,2),(1,3)]
for (i,j) in coordinates:
print i,j
Solution 2
Extracting the first (or second) coordinate is simple, and it's a python idiom you should know:
[ i for i, j in coordinates ]
However, this does not match your example output (and would give five values, not six). So... who knows what you mean. As for the rest of your tasks, I can't even guess wrong. You'll need to clarify your goal or wait for someone who can read your mind.
Admin
Updated on June 04, 2022Comments
-
Admin over 1 year
coordinates = [(i, j) for i, row in enumerate(mymatrix) for j, v in enumerate(row) if v == '0']
I have a list of coordinates (tuples) and would like to print the coordinate, the nearest tuple to the right of the coordinate and the next tuple within the same column as the coordinate. How would I do this for each coordinate?
For example:
coordinates = [(0,0),(0,3),(1,0),(1,2),(1,3)]
Output for the first coordinate would be:
0 0 0 3 1 0
Output for the second coordinate would be:
0 3 -1 -1 1 3