[英]How to conditionally modify a list with python
I have a list我有一个清单
bigdumblist = [(0, 0, {'product_id': 2, 'product_uom_qty': 237}), (0, 0, {'product_id': 1, 'product_uom_qty': 1})]
I want the list to be modified as such我希望这样修改列表
# ***pseudocode***
if 'product_id' ==2 change to 3 if 'product_uom_qty' >= 45 divide by 45
new list新名单
bigdumblist = [((0, 0, {'product_id': 3, 'product_uom_qty': 5})), (0, 0, {'product_id': 1, 'product_uom_qty': 1})]
I have tried to research but have found a way to change the values of certain items on the list.我曾尝试进行研究,但找到了一种方法来更改列表中某些项目的值。 I know I can use indexing to access the list but is there a way to access items on the list based on the items themselves?我知道我可以使用索引来访问列表,但是有没有办法根据项目本身访问列表中的项目?
Instead of thinking about it as a list, it's easier to think of what you want to do with a single item.与其将其视为一个列表,不如更容易地想到要对单个项目做什么。
def repair_item(item):
if item["product_id"] == 2:
item["product_id"] = 3
if item["product_uom_qty"] >= 45:
item["product_uom_qty"] /= 45
Now, simply loop over all the items:现在,只需遍历所有项目:
for _, _, item in my_list:
repair_item(item)
You can just iterate through the list: Below is Python code that does just that:您可以遍历列表:下面是 Python 代码,它就是这样做的:
bigdumblist = [(0, 0, {'product_id': 2, 'product_uom_qty': 237}), (0, 0, {'product_id': 1, 'product_uom_qty': 1})]
for tup in bigdumblist:
# Iterates through the tuples in bigdumblist
for item in tup:
# Checks if the item in the tuple is a dictionary
if type(item) == dict:
# Does specified changes to the dictionary
if item["product_id"] == 2:
item["product_id"] = 3
if item["product_uom_qty"] >= 45:
item["product_uom_qty"] /= 45
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.