Python将两个列表组合成一个字典

时间:2017-04-25 02:33:00

标签: python

我有两个列表,我想将它们组合成一个字典。

def make_list():

   item_list = []

   print('Enter data for three items.')
   for count in range(1, 4):
       print('Item Number ' + str(count) + ':')
       item = input('Enter the description of item: ')
       units = float(input('Enter the number of units in inventory: '))
       price = float(input('Enter the price per item: '))
       print()

       items = retailitem.RetailItem(item, units, price)

       item_list.append(items)

   return item_list

我想在a = 0时重复列表b。

a = [0,1,2,3,4,5,6,0,1,2,3,4,5,6]
b = [1,2]

编写这样的代码的pythonic方式是什么?

1 个答案:

答案 0 :(得分:1)

获得类似输出的唯一方法是切出列表并在b中保留c的唯一键

我不知道有什么pythonic方式

from collections import deque

a = [0,2,3,4,5,6,0,1,2,3,4,5,6,0,3]
b = [1,2,3]

if not a.count(0) == len(b):
    raise RuntimeError("not enough zeros")

c = {}

idx = a.index(0)
q = deque(b)
while q:
    try:
        next_idx = a.index(0, idx+1)
        head, a = a[0:next_idx], a[next_idx:]
        val = head
    except ValueError as e:
        val = a
    c[q.popleft()] = val
    idx = next_idx

{1: [0, 2, 3, 4, 5, 6], 2: [0, 1, 2, 3, 4, 5, 6], 3: [0, 3]}

或者,作为元组的评论并受到这篇文章的启发

Split a list into nested lists on a value

import itertools
def isplit(iterable,splitters):
    return [list(g) for k,g in itertools.groupby(iterable,lambda x: x in splitters) if not k]

split_on = 0
groups = zip(b, map(lambda s: [split_on] + s, isplit(a, (split_on, ))))
for g in groups:
    print(g)

输出

(1, [0, 2, 3, 4, 5, 6])
(2, [0, 1, 2, 3, 4, 5, 6])
(3, [0, 3])