Home > Software engineering >  Print every two pairs in a new line from array of elements in Python
Print every two pairs in a new line from array of elements in Python

Time:11-26

How can I print from an array of elements in Python every second pair of elements one below another, without commas and brackets?

My array looks like this:

m=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

And, I want to print in one of the cases:

1 2
5 6
9 10

or in another case:

3 4
7 8
11 12

I didn't know how to do that, so i created two separate arrays, but when i try to print elements in separate rows, each pair has brackets and coma. Is there any way to solve this easier and to make it look as i wrote?

What I've tried:

a=[m[j:j 2] for j in range(0,len(m),2)]
a1=m[::2]
a2=m[1::2]

if s1>s2:
  print("\n".join(map(str,a1)))
elif s1<s2:
  print("\n".join(map(str,a2)))

My current output:

[3, 4]
[7, 8]
[11, 12]

CodePudding user response:

You could use a while loop

m = [1,2,3,4,5,6,7,8,9] 
idx = 0
try:
    while idx < len:
        print(m[idx], m[idx 1]) 
        idx  = 3
except IndexError:
    print("Index out of bounds") 

Just change the start Index (idx) for the other print

CodePudding user response:

Another way to do it like this-

m=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
pairs = [[i, i 1] for i in m[::2]]
results = [], []
for i, e in enumerate(pairs):
   results[i%2].append(e)

for i in results:
    for p in i:
       print(*p)
    print("-----")

Output:

1 2
5 6
9 10
-----
3 4
7 8
11 12
-----

CodePudding user response:

I don't understand why all the solutions are so complex, this is as simple as follows (case 1):

for i in range(0, len(m), 4):
    print(f"{m[i]} {m[i   1]}")

For case 2, just start the range with 2.

CodePudding user response:

what you are trying to achieve is making a pair of 2 in array and save alternative pair in a different arrays/list. one way of achiving this is below code, by going step by step.

m=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
make_pair = [(m[i], m[i 1]) for i in range(0, len(m), 2)]

res1 = []
res2 = []

print(make_pair)
# [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]
for i in range(len(make_pair)):
    if i%2:
            res2.append(make_pair[i])
    else:
            res1.append(make_pair[i])


print(res1)
# [(1, 2), (5, 6), (9, 10)]
print(res2)
# [(3, 4), (7, 8), (11, 12)]

if you want to go in one go, ie without creating pair array, then using temporary stack you can achieve same result

  • Related