我在迭代列表列表时发现了一些不一致的行为,我希望有人能帮我理解发生了什么。
我有一个参数字典: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
,或者可能包含letters
,numbers
和names
(甚至包含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()))
答案 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']]