-1
class Weightcheck:

def bag_products(self,product_list):
    bag_list = []
    non_bag_items = []
    MAX_BAG_WEIGHT = 5.0

    for product in product_list:
        if float(product['weight']) > MAX_BAG_WEIGHT:
            product_list.remove(product)
            non_bag_items.append(product)

和参数 product_list 就像

product_list = {'barcode': [123, 456], 'Name': ['Milk, 2 Litres', 'Bread'], 'Price': ['2', '3.5'], 'weight': ['2', '0.6']}

如果通过的参数就像

product_list = [{'name': 'Milk', 'price': 2.0, 'weight': 2.0},
            {'name': 'LowfatMilk', 'price': 2.0, 'weight': 2.0},
            {'name': 'HighfatMilk', 'price': 2.0, 'weight': 2.0},
            {'name': 'Bread', 'price': 2.0, 'weight': 7.0}]

然后它可以正常工作。我的意思是字典列表。请帮助我如何解决这个问题

4

2 回答 2

1

这不是最好的方法,但你可以使用这样的东西:

final_list = [] 
for i in range(len(product_in_basket['Name'])):
    item ={} # each new item
    for k,v in product_in_basket.items():
        item[k]= v[i] # filling that item with specific index
    final_list.append(item) # append to final list

> final_list
[
  {'Name': 'Milk, 2 Litres', 'Price': '2', 'barcode': 123, 'weight': '2.0'},
  {'Name': 'Bread', 'Price': '3.5', 'barcode': 456, 'weight': '0.6'}
]
于 2018-04-28T03:52:51.270 回答
0

这是一个可以解决问题的单线:

product_list = [dict(zip(product_in_basket,t)) for t in zip(*product_in_basket.values())]

print(product_list)

输出:

[{'Name': 'Milk, 2 Litres', 'Price': '2', 'barcode': 123, 'weight': '2.0'}, {'Name': 'Bread', 'Price': '3.5', 'barcode': 456, 'weight': '0.6'}]

一般来说,最好不要使用纯 Python 的库,但我认为使用 pandas 的解决方案可能会很有趣:

import pandas as pd

product_in_basket = {'barcode': [123, 456], 'Name': ['Milk, 2 Litres', 'Bread'],
                 'Price': ['2', '3.5'], 'weight': ['2.0', '0.6']}

df = pd.DataFrame(product_in_basket)

output = list(df.T.to_dict().values())

print(output)

输出:

[{'Name': 'Milk, 2 Litres', 'Price': '2', 'barcode': 123, 'weight': '2.0'},
 {'Name': 'Bread', 'Price': '3.5', 'barcode': 456, 'weight': '0.6'}]
于 2018-04-28T03:58:41.577 回答