简体   繁体   中英

How to print a list of pairs without commas between pairs in python?

I have two lists of the same size

a = [1, 2, 3, 4, 5]

and

b = [2, 3, 4, 5, 6]

I would like to print the zipped list zip(a, b) but without commas between pairs as follows:

c = [(1, 2) (2, 3) (3, 4) (4, 5) (5, 6)]

When I do

print(str(list(zip(a, b))).replace(',', ''))

I get

[(1 2) (2 3) (3 4) (4 5) (5 6)]

which removes all commas even the ones inside each pair, (1 2) .

I want the output to be like

[(x, y) (z, t) (u, v) ...]

您可以为replace使用更具体的参数:

print(str(list(zip(a, b))).replace('), (', ') ('))
print("[" + " ".join(map(str, zip(a, b))) + "]")

或者

print("[", " ".join(map(str, zip(a, b))), "]", sep="")

you can use f-string with str join

f"[{', '.join([str(e).replace(',','') for e in c])}]"

or you can use regular expression:

import re 

re.sub('\([^()]*\)', lambda x: x.group().replace(",", ""), str(c))

output:

[(1 2), (2 3), (3 4), (4 5), (5 6)]

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