akira
akira

Reputation: 531

Tuple item printing format

I have a two list of tuple as follows.I want to print this tuples separated by ‘|’.How an I achieve this.

listoftuple =[(1,2),(3,4),(5,6)]
listoftuple1 =[(3,4,5),(5,6,7),(9,0,9)]

I want the result to be printed as follows:

1|2 3|4 5|6
3|4|5 5|6|7,9|0|9

Upvotes: 1

Views: 104

Answers (5)

MervS
MervS

Reputation: 5902

The other answers are excellent. Alternatively:

' '.join(["|".join(str(k) for k in j) for j in listoftuple1])

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304147

Here is a Python3 answer (or python2 if you use from __future__ import print_function)

>>> class my_tup(tuple):
...     def __repr__(self):
...         return "|".join(repr(x) for x in self)
... 
>>> lot =[(1,2),(3,4),(5,6)]
>>> print(*map(my_tup, lot))
1|2 3|4 5|6
>>> lot =[(3,4,5),(5,6,7),(9,0,9)]
>>> print(*map(my_tup, lot))
3|4|5 5|6|7 9|0|9

If you have an objection to more than one line of code, as some here obviously do :)

print(*("|".join(repr(x) for x in y) for y in lot))

Upvotes: 1

The6thSense
The6thSense

Reputation: 8335

Making it simple using for loop, map and join

Code:

listoftuple = [(1, 2), (3, 4), (5, 6)]
listoftuple1 = [(3, 4, 5), (5, 6, 7), (9, 0, 9)]

for lst1 in listoftuple:
    print "|".join(map(str, list(lst1))),

print ""

for lst2 in listoftuple1:
    print "|".join(map(str, list(lst2))),

Output:

1|2 3|4 5|6 
3|4|5 5|6|7 9|0|9

Now making it a little complicated and less readable

Code2:

print " ".join("|".join(map(str, list(lst2))) for lst2 in listoftuple1)
print " ".join("|".join(map(str, list(lst1))) for lst1 in listoftuple)

Upvotes: 2

TigerhawkT3
TigerhawkT3

Reputation: 49318

You can map each tuples elements to str and then join them, then unpack a generator for that to a print() call with a custom separator:

>>> listoftuple = [(1,2),(3,4),(5,6)]
>>> print(*('|'.join(map(str, t)) for t in listoftuple), sep=' ')
1|2 3|4 5|6
>>> print(*('|'.join(map(str, t)) for t in listoftuple1), sep=' ')
3|4|5 5|6|7 9|0|9

If you're using Python 2 rather than 3, you'll need from __future__ import print_function.

Upvotes: 1

pkacprzak
pkacprzak

Reputation: 5629

>>> " ".join(map(lambda x: "|".join(map(str, x)), listoftuple1))
'3|4|5 5|6|7 9|0|9'

Upvotes: 5

Related Questions