【问题标题】:Formatting tuples when printing output (calculating volume)打印输出时格式化元组(计算体积)
【发布时间】:2020-10-15 17:54:47
【问题描述】:

我目前无法为此项目/作业 (python 3.8) 格式化输出。

我必须提示用户输入立方体、金字塔或椭圆体,并计算输入形状的体积。在用户为所有 3 个形状计算了许多不同的体积后,程序必须输出不同形状的列表以及它使用列表为每个形状计算的所有体积。该列表必须是(shapename,volume)形式的元组。例如,列表可能如下所示:[(“cube”,1.00),(“cube”,9.00)]。我还必须使用卷的值从最低到最高对列表进行排序。

我的输出看起来像这样,几乎是正确的,我只需要想办法从显示形状名称和相应体积的底部 4 行中删除括号、引号和逗号。

Please enter shape (quit/q, cube/c, pyramid/p, ellipsoid/e): pyramid
Enter the base of the pyramid: 12
Enter the height of the pyramid: 16
The volume of a pyramid with base 12.0 and height 16.0 is:   768.00

Please enter shape (quit/q, cube/c, pyramid/p, ellipsoid/e): p
Enter the base of the pyramid: 4
Enter the height of the pyramid: 8
The volume of a pyramid with base 4.0 and height 8.0 is:   42.67

Please enter shape (quit/q, cube/c, pyramid/p, ellipsoid/e): cube
Enter length of side for the cube: 11
The volume of a cube with side 11.0 is:   1331.00

Please enter shape (quit/q, cube/c, pyramid/p, ellipsoid/e): e
Enter the first radius: 7
Enter the second radius: 8
Enter the third radius: 9
The volume of an ellipsoid with radii 7.0 and 8.0 and 9.0 is:   2111.15

Please enter shape (quit/q, cube/c, pyramid/p, ellipsoid/e): quit
Output: Volume of shapes entered in sorted order:
('pyramid', 42.67)
('pyramid', 768.0)
('cube', 1331.0)
('ellipsoid', 2111.15)

作为参考,这是我的代码的一部分,它应该打印列表中的每个项目/元组:

elif shapeName == "quit" or shapeName == "q" :
        print ("Output: Volume of shapes entered in sorted order:")
        myList.sort(key = lambda myList: myList[1])
        for item in myList:
                print (item)
        exit()

【问题讨论】:

  • 也许是这个? print(f"item[0]} {item[1]}")
  • 您可以索引元组并使用string formatting 以您想要的任何格式打印。到目前为止,您尝试过什么?

标签: python list function tuples


【解决方案1】:

我认为这可以帮助你...

for item in myList:
    print (*item, sep=" : ")

【讨论】:

  • 很好,我忘记了分隔符!
【解决方案2】:

您可以提取每个项目的值,并打印出来:

for item in l:
    shapename, volume = item
    print(f"{shapename}, {volume}")  

输出:

pyramid, 42.67
pyramid, 768.0
cube, 1331.0
ellipsoid, 2111.15

如果你不关心逗号,你也可以试试这个:

for item in l:
    print(*item)

输出

pyramid 42.67
pyramid 768.0
cube 1331.0
ellipsoid 2111.15

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多