简体   繁体   中英

How to print a list of tuples without commas in Python?

I have two lists in python.

a = [1, 2, 4, 8, 16]
b = [0, 1, 2, 3, 4]

and a third list c that is the zip of them.

c = zip(a, b) 

or simply I have a list of tuples like this:

c = [(1, 0), (2, 1), (4, 2), (8, 3), (16, 4)]

I would like to print the list c without the commas after the parentheses. Is there a way to do this in Python?

I would like to print the list c like this:

[(1, 0) (2, 1) (4, 2) (8, 3) (16, 4)]
print('[%s]' % ' '.join(map(str, c)))

Prints:

[(1, 0) (2, 1) (4, 2) (8, 3) (16, 4)]

for your inputs.

You can basically take advantage of the fact that you're using the natural string representation of the tuples and just join with a space.

print('[' + ' '.join([str(tup) for tup in c]) + ']')

Using a list comprehension to create a list of the tuples in string form. Those are then joined and the square brackets are added to make it look as you want it.

Would it be okay to create the final result as a string?

c_no_comma = ''
for element in c:
    c_no_comma += str(element) + ' '

c_no_comma = '[ ' + c_no_comma + ']'

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