Reputation: 7
counter = 0
cord =[1,2,21,12,2,44,5,13,15,5,19,21,5]
for i in cord:
if (counter ==0):
x=i
if (counter ==1):
y =i
if (counter ==2):
z= i
counter = counter+1
print(x,y,z)
Output
1 2 21
But I want output in pairs of 3. for example- (1,2,21) (12,2,44) like wise
Upvotes: 0
Views: 253
Reputation: 120409
Use zip
and slice:
>>> list(zip(cord[::3], cord[1::3], cord[2::3]))
[(1, 2, 21), (12, 2, 44), (5, 13, 15), (5, 19, 21)]
Printing
lst = zip(cord[::3], cord[1::3], cord[2::3])
print(*lst, sep='\n')
(1, 2, 21)
(12, 2, 44)
(5, 13, 15)
(5, 19, 21)
Upvotes: 2
Reputation: 1499
You should save it to list or tuple with 3 pairs:
counter = 0
cord =[1,2,21,12,2,44,5,13,15,5,19,21,5]
point=[]
for i in cord:
point.append(i)
counter = counter+1
if counter==3:
print(point)
point=[]
counter=0
Upvotes: 0
Reputation: 30926
This might be a bit tedious but can be useful.
def divide(lst, n):
for i in range(0, len(lst), n):
yield lst[i:i + n]
for x in divide(cord,3):
print(x)
So the thing is, here you will also get a list with one element and process it further. (Maybe you can filter as per length or something similar).
Upvotes: 0
Reputation: 1108
Easiest method is to just iterate in threes, see below:
cord = [1,2,21,12,2,44,5,13,15,5,19,21,5]
for i in range(0, len(cord), 3):
x = cord[i]
y = cord[i + 1]
z = cord[i + 2]
print(x, y, z)
For a better answer that'll preserve the list, see How to group elements in python by n elements
Upvotes: 1
Reputation: 24049
try this:
[tuple(cord[i:i+3]) for i in range(0,len(cord),3)]
# [(1, 2, 21), (12, 2, 44), (5, 13, 15), (5, 19, 21), (5,)]
print(*[tuple(cord[i:i+3]) for i in range(0,len(cord),3)])
# (1, 2, 21) (12, 2, 44) (5, 13, 15) (5, 19, 21) (5,)
Upvotes: 1