如何过滤python列表?

时间:2017-09-23 06:40:39

标签: python json

我有一个列表,我需要过滤该列表并获取一些关键值。这是清单:

"products":[  
      {  
         "discount":"0.00000",
         "id":"6f47e339-34a0-8c58-11e7-9f96677d9fcc",
         "loyalty_value":"0.00000",
         "price":"0.00000",
         "price_set":false,
         "price_total":"0.00000",
         "product_id":"0af7b240-ab09-11e7-eddc-8cb82351211c",
         "quantity":1,
      },
      {  
         "discount":"0.00000",
         "id":"6f47e339-34a0-8c58-11e7-9f966ecf8e5f",
         "loyalty_value":"0.00000",
         "price":"3.18182",
         "price_set":false,
         "price_total":"3.18182",
         "product_id":"0af7b240-ab09-11e7-eddc-80d691bbf094",
         "quantity":1,
      },
      {  
         "discount":"0.00000",
         "id":"6f47e339-34a0-8c58-11e7-9f96701777b2",
         "loyalty_value":"0.00000",
         "price":"2.72727",
         "price_set":false,
         "price_total":"2.72727",
         "product_id":"0af7b240-ab09-11e7-eddc-80a522346b58",
         "quantity":1,
      }

   ]

我需要在过滤后从上面的列表中获取相同的列表,如:

"LstProduct": [
    {
      "product_id": "string",
      "price": 0,
      "quantity": 0
    },
    {
      "product_id": "string",
      "price": 0,
      "quantity": 0
    }, 
    {
      "product_id": "string",
      "price": 0,
      "quantity": 0
    }
  ]

1 个答案:

答案 0 :(得分:2)

您可以创建一个新列表,其中包含新列表所需的密钥。然后,您可以使用 list comprehension 过滤结果:

a = 3 #this is a in ax+b
b = 1 #this is b in ax+b
t = 3 #this is time in seconds

x = 1
for i in range(t):
    i+=1
    x=(a*x)+b
print(str(x) + ' candies after '+str(i)+' seconds')

其中filtered_keys = ["product_id", "price", "quantity"] new_list = [{key: element[key] for key in filtered_keys} for element in old_list] 是您的dict对象列表。