【发布时间】:2021-06-06 02:52:06
【问题描述】:
我正在尝试找到一种方法来从 python 中的现有字典中打印出一个新列表。我希望能够根据字典中的条目为每种织物类型创建一个新列表,而不是打印出整个字典。我仍然是一个试图弄清楚的初学者。所有其他方式都会导致错误。这是我到目前为止的代码,但我觉得必须有一种比重复打破同一任务的循环更简单的方法。有什么建议吗?
Clothes_in_Closet = [{
"type" : "sweater",
"fabric" : "wool",
"size" : "s",
},
{
"type" : "shirt",
"fabric" : "cotton",
"size" : "m",
},
{
"type" : "jeans",
"fabric" : "cotton blend",
"size" : "m",
}
]
newList = [ ]
for fabrics in Clothes_in_Closet:
fabrics = Clothes_in_Closet [0]["fabric"]
newList.append(fabrics)
break
for fabrics in Clothes_in_Closet:
fabrics = Clothes_in_Closet [1]["fabric"]
newList.append(fabrics)
break
for fabrics in Clothes_in_Closet:
fabrics = Clothes_in_Closet [2]["fabric"]
newList.append(fabrics)
break
print(newList)
【问题讨论】:
-
你想要什么
-
而不是
breaking,你不能这样做,而是使用fabrics,它将承担每个内部字典 - 所以你可以这样做for thing in Clothes_in_Closet: newList.append( thing["fabric"])
标签: python loops dictionary for-loop