item_new_name = []
name = [{'item__product_short_code': 'AAA', 'item_quantity': 20}, {'item__product_short_code': 'BBB', 'item_quantity': 10}, {'item__product_short_code': 'CCC', 'item_quantity': 5}]
如何遍历此列表,以便得到以下结果:
item_new_name = ["AAA1","AAA2",...,"AAA20","BBB1","BBB2",...,"BBB10","CCC1",..."CCC5"]
我做了什么”:
for i in so_items:
print("i",i)
for k,v in i.items():
print("v",v)
for k in range(int(v["item_quantity"])):
print("k",k)
错误:
TypeError: string indices must be integers
答案 0 :(得分:1)
您可以使用列表理解:
name = [{'item__product_short_code': 'AAA', 'item_quantity': 20}, {'item__product_short_code': 'BBB', 'item_quantity': 10}, {'item__product_short_code': 'CCC', 'item_quantity': 5}]
item_new_name = [e for d in name for e in (d['item__product_short_code'] + str(i) for i in range(1, d['item_quantity'] + 1))]
输出:
['AAA1',
'AAA2',
'AAA3',
'AAA4',
'AAA5',
'AAA6',
'AAA7',
'AAA8',
'AAA9',
'AAA10',
'AAA11',
'AAA12',
'AAA13',
'AAA14',
'AAA15',
'AAA16',
'AAA17',
'AAA18',
'AAA19',
'AAA20',
'BBB1',
'BBB2',
'BBB3',
'BBB4',
'BBB5',
'BBB6',
'BBB7',
'BBB8',
'BBB9',
'BBB10',
'CCC1',
'CCC2',
'CCC3',
'CCC4',
'CCC5']