将参数字典翻译成密钥列表

时间:2017-08-11 15:03:05

标签: python arrays python-2.7 list multidimensional-array

我在迭代列表列表时发现了一些不一致的行为,我希望有人能帮我理解发生了什么。

我有一个参数字典:params = {'letters': ['a', 'b', 'c', 'd', 'e'], 'numbers': ['1', '2']},我想把它们转换成一个键列表,其中一个键是参数的排列,所以键是[['a', '1'], ['a', '2'], ['b', '1'], ['b', '2'], ['c', '1'], ['c', '2'], ['d', '1'], ['d', '2']]

编辑:当params可扩展时,这变得棘手。 params可能只包含letters,或者可能包含lettersnumbersnames(甚至包含10种不同的内容)。这就是for letter in params['letters']: for number in params['numbers']: blah之类的东西不起作用的原因。

我的代码:

    keys = []
    params = {'letters': ['a','b','c','d'], 'numbers': ['1', '2']}

    for param in params:
      if not keys:
        for thing in params[param]:
          keys.append([thing])
        print keys
        continue
      cur_len = len(keys)
      keys *= len(params[param])
      print keys
      print '\n'
      for idx, key in enumerate(keys):
        key.append(params[param][idx/cur_len])
        print keys, '\n'

输出:

    [['a', '1'], ['b'], ['c'], ['d'], ['a', '1'], ['b'], ['c'], ['d']]

    [['a', '1'], ['b', '1'], ['c'], ['d'], ['a', '1'], ['b', '1'], ['c'], ['d']]

    ...

    [['a', '1'], ['b', '1'], ['c', '1'], ['d', '1'], ['a', '1'], ['b', '1'], ['c', '1'], ['d', '1']]

    [['a', '1', '2'], ['b', '1'], ['c', '1'], ['d', '1'], ['a', '1', '2'], ['b', '1'], ['c', '1'], ['d', '1']]

    ...

    [['a', '1', '2'], ['b', '1', '2'], ['c', '1', '2'], ['d', '1', '2'], ['a', '1', '2'], ['b', '1', '2'], ['c', '1', '2'], ['d', '1', '2']]

为什么数字会附加到索引0和4,然后是1和5等?

答案(以下信用Martin Evans): 如果params是OrderedDict

,这种方法效果最佳
    from itertools import product
    from collections import OrderedDict

    params = OrderedDict()
    params['letters'] = ['a','b','c','d']
    params['numbers'] = ['1', '2']
    keys = list(product(*params.keys()))

1 个答案:

答案 0 :(得分:0)

这太复杂了。想想它,因为你正试图获取每个字母,每个数字组合。有几种方法可以做到这一点:

keys = []
params = {'letters': ['a', 'b', 'c', 'd'], 'numbers': ['1', '2']}

最基本的方法:

for x in params['letters']:
    for y in params['numbers']:
        keys.append([x, y])

单行:

output = [[x,y] for x in params['letters'] for y in params['numbers']]

print(keys)
print(output)

输出

[['a', '1'], ['a', '2'], ['b', '1'], ['b', '2'], ['c', '1'], ['c', '2'], ['d', '1'], ['d', '2']]
[['a', '1'], ['a', '2'], ['b', '1'], ['b', '2'], ['c', '1'], ['c', '2'], ['d', '1'], ['d', '2']]