简体   繁体   中英

How can I loop over a tuple with two tuple elements and print a nice formatted string result of multiplying the tuple elements?

I am trying to get the output to print nicely so that it is more readable. This is what I have so far:

a = (4,4)
b = (25,75)
c = (8,9)
d = (88,4)

elements = [(a[0]*a[1], "= 4 x 4"), 
(b[0]*b[1], "= 25 x 75"),
(c[0]*c[1], "= 8 x 9"),
(d[0]*d[1], "= 88 x 4")]

fmt = "{0:>4}" # Something along these lines, not specific

for i in elements:
    print(fmt.format(i)) 

This is the output i get:

(16, '= 4 x 4')
(1875, '= 25 x 75')
(72, '= 8 x 9')
(352, '= 88 x 4')

I recognize that my 'elements' tuple is quite sloppy, but it is the best I could come up with so far! I am looking to try and format my output to be nice and readable like this:

  16 =  4 x  4

1875 =  25 x  75

  72 = 8 x 9

 352 =  88 x  4

Thanks for the help.

inp = [(4,4), (25,75), (8,9), (88,4)]

for eq in inp:
  print('{:>4} = {:>2} × {:>2}'.format(eq[0] * eq[1], eq[0], eq[1]))

How about:

inp = [(4,4), (25,75), (8,9), (88,4)]
print '\n'.join(['{:>4} = {:>2} × {:>2}'.format(x, y, x * y) for x, y in inp])

Should be faster and more convenient if it is going to be part of a function.

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