[英]Add iteration counter to dict/list comprehension python
I want to add an iteration counter to my list comprehension so that each key will have its own number based on which iteration we are on我想在我的列表理解中添加一个迭代计数器,以便每个键都有自己的编号,具体取决于我们正在进行的迭代
currently:目前:
itemdict = {item.name: [item.size, item.price] for item in items}
Which gives: {ItemNameExample: ['size=15', 'price=100']}
其中给出: {ItemNameExample: ['size=15', 'price=100']}
I want to do something like:我想做类似的事情:
counter = 0
itemdict = {str(counter+=1) +'. '+ item.name: [item.size, item.price] for item in items}
Which would give me sometime like: {1. ItemNameExample: ['size=15', 'price=100']}
这会给我一个像: {1. ItemNameExample: ['size=15', 'price=100']}
{1. ItemNameExample: ['size=15', 'price=100']}
But the above code I tried always gives a 1
rather than adding to the count based on iteration但是我尝试的上述代码总是给出1
而不是基于迭代添加到计数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.