简体   繁体   English

如何打开包装并打印元组

[英]How to unpack and print a tuple

I am a beginner in Python (3.x), this is my first post here, and I am trying to unpack a tuple, then print it with a certain format (my words may not be quite right). 我是Python(3.x)的初学者,这是我在这里的第一篇文章,我试图解包一个元组,然后用某种格式打印它(我的话可能不太正确)。 Here is what I have: 这是我有的:

w = 45667.778
x = 56785.55
y = 34529.4568
z = 789612.554

nums = (w, x, y, z)
hdr62 = '{:>15} {:>15} {:>15} {:>15}'

print(tuple('${:,.0f}'.format(num).rjust(12, ' ') for num in nums))

What/how do I alter to unpack and then use the hdr62 format to print the tuple? 我如何更改解压缩然后使用hdr62格式打印元组?

Maybe I'm missing things, but if you just want to format the tuple nums according to the hdr62 format, then you can just call str.format on it and pass in the numbers as unpacked tuple: 也许我错过了一些东西,但是如果你只是想根据hdr62格式格式化元组nums ,那么你可以在它上面调用str.format并将数字作为解包后的元组传递:

>>> print(hdr62.format(*nums))
      45667.778        56785.55      34529.4568      789612.554

If you actually want to run another format on the tuple items first, you can do that separately: 如果您确实想首先在元组项上运行另一种格式,则可以单独执行此操作:

>>> ['${:,.0f}'.format(n) for n in nums]
['$45,668', '$56,786', '$34,529', '$789,613']
>>> print(hdr62.format(*['${:,.0f}'.format(n) for n in nums]))
        $45,668         $56,786         $34,529        $789,613

Based on your question and the comments below, you can first use the tuple comprehension to format your numbers and then call the formatting. 根据您的问题和下面的注释,您可以先使用元组理解来格式化数字,然后调用格式。 The format call can be done with an asterisk ( * ), so: format调用可以使用星号( * )完成,因此:

nums2 = tuple('${:,.0f}'.format(num).rjust(12, ' ') for num in nums)
print(hdr62.format(*nums2))

If you call a function and use an asterisk, the parameter (which should be a sequence) behind the curtains Python unpacks the sequence and feed it as separate parameters, so in this case: 如果你调用一个函数并使用一个星号,那么幕后面的参数(应该是一个序列)Python解压缩序列并将其作为单独的参数提供,所以在这种情况下:

nums2 = tuple('${:,.0f}'.format(num).rjust(12, ' ') for num in nums)
print(hdr62.format(*nums2))

is equivalent to: 相当于:

nums2 = tuple('${:,.0f}'.format(num).rjust(12, ' ') for num in nums)
print(hdr62.format(nums[0],nums[1],nums[2],nums[3]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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