[英]Replacing elements of a list in python
I have the original list with dictionaries inside it for 3 drinks and their corresponding prices and stock levels.我有原始列表,其中包含 3 种饮料的字典及其相应的价格和库存水平。
products = [
{
"name": "coke",
"price": 3,
"stock": 10
},
{
"name": "bepis",
"price": 2,
"stock": 232
},
{
"name": "fanta",
"price": 2,
"stock": 144
}
[
If I had 3 lists such as these:如果我有 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
As seen above there are 3 new lists but now there are 4 total drinks.如上所示,有 3 个新列表,但现在总共有 4 个饮料。 The lists correspond to each other eg mdew - 3 - 10, water 10 - 10, tea - 3 - 10, tapwater - 40 - EMPTY.
这些列表相互对应,例如 mdew - 3 - 10、water 10 - 10、tea - 3 - 10、tapwater - 40 - EMPTY。
How could I go about recreating the first list, replacing the values with the 3 lists?我怎么能 go 关于重新创建第一个列表,用 3 个列表替换值? Sorry if this was poorly worded.
对不起,如果这措辞不好。
Thank you!谢谢!
You'd ordinarily use zip()
to "zip up" multiple iterables to iterate over simultaneously:您通常会使用
zip()
来“压缩”多个可迭代对象以同时进行迭代:
for (name, price, stock) in zip(names, prices, stocks):
print(f"{name=}, {price=}, {stock=}")
The output would be output 将是
name='mdew', price='3', stock='10'
name='water', price='10', stock='10'
name='tea', price='3', stock='10'
– notice the conspicuous lack of tap water. – 注意自来水明显不足。
Since one iterable is shorter than the others, you'll need itertools.zip_longest
.由于一个可迭代对象比其他可迭代对象短,因此您需要
itertools.zip_longest
。
After that, generating a list of dicts is just a list comprehension away.在那之后,生成一个字典列表只是一个列表理解。
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)
The output is 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},
]
EDIT:编辑:
If you don't want to use itertools
(for whichever reason), you can write something like zip_longest
yourself (this is intentionally simplified to require len()
able iterables):如果您不想使用
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.