[英]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.