【问题标题】:Print a new list from a dictionary? [duplicate]从字典中打印一个新列表? [复制]
【发布时间】: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


【解决方案1】:

使用列表推导并获取与键 fabric 关联的值:

newList = [cloth['fabric'] for cloth in Clothes_in_Closet]
print(newList)

输出:

['wool', 'cotton', 'cotton blend']

您也可以使用传统的循环方法来代替列表推导,但请注意,列表推导优于 Python 中的传统循环:

newList = []
for cloth in Clothes_in_Closet:
    newList.append(cloth['fabric'])
    
print(newList)

【讨论】:

  • 如果您只需要唯一值,则进一步将set() 应用于结果为set(newList)
猜你喜欢
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
  • 2017-04-26
  • 2015-10-04
  • 2017-08-20
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多