如何使用列表在Python中打印句子

如何使用列表在Python中打印句子,python,Python,我有这个数据列表 [ {"type": "Square", "area": 150.5}, {"type": "Rectangle", "area": 80}, {"type": "Rectangle", "area": 660}, {"type": "Ci

我有这个数据列表

[
    {"type": "Square", "area": 150.5},
    {"type": "Rectangle", "area": 80},
    {"type": "Rectangle", "area": 660},
    {"type": "Circle", "area": 68.2},
    {"type": "Triangle", "area": 20}
]
我想定义一个对象来表示这个数据,它从“type”和“area”中获取值并将其存储在一个类中(我称这个类对象)

以下是我试图做的:

    def __init__(self, list):
        self.list = list 

然后从这个类中,我要打印出类中每个对象的类型和区域。

如果要打印,请使用
f string

listt = [
    {"type": "Square", "area": 150.5},
    {"type": "Rectangle", "area": 80},
    {"type": "Rectangle", "area": 660},
    {"type": "Circle", "area": 68.2},
    {"type": "Triangle", "area": 20}
]

for i in range(len(listt)):
    print(f'{i+1}- {listt[i]["type"]} with area size {listt[i]["area"]}')

>> 1- Square with area size 150.5
   2- Rectangle with area size 80
   3- Rectangle with area size 660
   4- Circle with area size 68.2
   5- Triangle with area size 20

这很简单。你应该试着自己先弄清楚这些事情

for idx, val in enumerate(your_list, start=1):
    print(f'{idx} - {val["type"]} with area size {val["area"]}')

你试过什么?显示一些代码。您希望它打印它还是将它存储在某个变量中?
['{}-{type}区域大小为{area}。在枚举(listt,1)中为i,el设置格式(i,**el)]
他想打印它。不想存储在列表中..是的,我知道,我只是使用列表理解作为循环的简短形式向您展示了使用
enumerate()
str.format()
可以使您的代码看起来更好(imho)
打印({}-{type},面积大小为{area})。format(idx,**val))
@OlvinRoght为什么您更喜欢
.format()
?对我来说,它不是那么可读的^^“您可以在中使用start=1参数enumerate@c0mr4t,我之所以使用它,是因为它接受关键字参数,所以您可以只解压缩dict而不是单独获取每个值。@OlvinRoght-ya好的,我想这只是个人偏好。但我明白您的意思。