[英]Replacing elements of a list in python
我有原始列表,其中包含 3 种饮料的字典及其相应的价格和库存水平。
products = [
{
"name": "coke",
"price": 3,
"stock": 10
},
{
"name": "bepis",
"price": 2,
"stock": 232
},
{
"name": "fanta",
"price": 2,
"stock": 144
}
[
如果我有 3 个这样的列表:
["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 个饮料。 这些列表相互对应,例如 mdew - 3 - 10、water 10 - 10、tea - 3 - 10、tapwater - 40 - EMPTY。
我怎么能 go 关于重新创建第一个列表,用 3 个列表替换值? 对不起,如果这措辞不好。
谢谢!
您通常会使用zip()
来“压缩”多个可迭代对象以同时进行迭代:
for (name, price, stock) in zip(names, prices, stocks):
print(f"{name=}, {price=}, {stock=}")
output 将是
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)
output 是
[
{'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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.