我有最初的清单,里面有字典,里面有3种饮料,以及它们相应的价格和库存水平。
products = [
{
"name": "coke",
"price": 3,
"stock": 10
},
{
"name": "bepis",
"price": 2,
"stock": 232
},
{
"name": "fanta",
"price": 2,
"stock": 144
}
[如果我有三份这样的清单:
["mdew", "water", "tea", "tapwater"] # names
["3", "10", "3", "40"] # prices
["10", "10", "10"] # stock levels, tap water is out of stock so there are only 3 values here如上所示,有3个新的名单,但现在有4个总饮料。这些清单相互对应,如mde-3-10、水10-10、茶-3-10、自来水- 40 -空。
如何重新创建第一个列表,用3个列表替换值?如果这句话措辞不当,我很抱歉。
谢谢!
发布于 2022-09-16 08:20:15
您通常会使用zip()“压缩”多个可迭代性,以便同时进行迭代:
for (name, price, stock) in zip(names, prices, stocks):
print(f"{name=}, {price=}, {stock=}")输出将是
name='mdew', price='3', stock='10'
name='water', price='10', stock='10'
name='tea', price='3', stock='10'-注意到明显缺乏自来水。
因为一个可迭代性比其他迭代要短,所以您需要itertools.zip_longest。
在那之后,生成一个字典列表只是一个列表的理解。
import itertools
names = ["mdew", "water", "tea", "tapwater"]
prices = ["3", "10", "3", "40"]
stocks = ["10", "10", "10"]
products = [
{"name": name, "price": price, "stock": stock or 0}
for (name, price, stock) in itertools.zip_longest(names, prices, stocks)
]
print(products)输出是
[
{'name': 'mdew', 'price': '3', 'stock': '10'},
{'name': 'water', 'price': '10', 'stock': '10'},
{'name': 'tea', 'price': '3', 'stock': '10'},
{'name': 'tapwater', 'price': '40', 'stock': 0},
]编辑:
如果您不想使用itertools (无论出于什么原因),您可以自己编写类似于zip_longest的东西(这是有意简化为需要len()可迭代的):
def zip_longest_lists(*lists):
max_len = max(len(l) for l in lists)
for i in range(max_len):
yield tuple((l[i] if i < len(l) else None) for l in lists)https://stackoverflow.com/questions/73741870
复制相似问题