Data structure in Python

前端 未结 1 490
无人共我
无人共我 2021-01-29 16:48
names=[\'Peter\', \'John\']
size = [\'X\', \'M\', \'L\']
list_price =  [1, 2, 3, 4, 5, 6]  # There are 2 people will buy 3 size of shirt

I want to crea

相关标签:
1条回答
  • 2021-01-29 17:18

    You can turn list_price into an iterator and then use next to get one value after the other:

    >>> iterator = iter(list_price)
    >>> [{"name": n, "size_price": {s: next(iterator) for s in size}} for n in names]
    [{'size_price': {'X': 1, 'M': 2, 'L': 3}, 'name': 'Peter'}, 
     {'size_price': {'X': 4, 'M': 5, 'L': 6}, 'name': 'John'}]
    

    Of course you do not have to use a list comprehension but can do the same thing with nested loops as well.

    0 讨论(0)
提交回复
热议问题