简体   繁体   中英

How to do print in python in specific way

l = ['a1',1,'b1',2,'c1',3]

how to print like below(expected out)

a1 1
b1 2
c1 3

Do I need to do zip function for this? or any other way

Slice with a stride of 2 and zip with an offset slice:

l = ['a1',1,'b1',2,'c1',3]
for a, b in zip(l[::2], l[1::2]):
    print(a, b)

A for loop would do the trick (as mentioned in other answers)

But a list comprehension will also work:

[print(str(x[0]) + ' ' + str(x[1])) for x in zip(l[0::2], l[1::2])]

How does this work?

  • l[0::2] takes every element from l, starting at index 0, until the last element, and with steps of 2 (in other words it takes all the even elements)
  • l[1::2] takes all the odd elements
  • zip bundles those into a zip object (iterable tuples) of pairs
  • the last step is iterating over those and executing the print function for each of them

A for loop will solve the problem:

l = ['a1',1,'b1',2,'c1',3]
for index in range(0, len(l), 2):
    print(l[index] + " " + str(l[index+1]))

It starts at index 0 (at "a1") and goes in steps of 2 (jumping to "b1"). The print statement adds an offset of 1 to access the value in between.

Alternatives for the print statement itself, not changing the structure of the code:

print(l[index], str(l[index+1]), sep=" ")  # use space as a separator
print(f"{l[index]} {str(l[index+1])}")     # use f-string for formatting

You can use iter(object[, sentinel]) function as below

l = ['a1', 1, 'b1', 2, 'c1', 3]
I = iter(l)
for v in I:
   print(v, next(I), sep=" ")

For this i would recommend using dictionaries if its possible, i don't know what you are trying to do. Use them like this:

l = {'a1':1,'b1':2,'c1':3}

for key, value in l.items():
    print("{} {}".format(key, value))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM