打印输出时格式化元组(计算体积)

2024-06-28 19:08:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前无法格式化此项目/任务(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()

Tags: ofthepyramid列表base体积quit形状
2条回答

我想这可以帮助你

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

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

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

相关问题 更多 >