-6

Pythonでは、以下のような辞書があります

{'key1': [L1, L2],
 'key2': [P1, P2],
 'key3': [T1],
 'key4': [V1]}

望ましい出力は

{'key1': [L1], 'key2': [P1], 'key3': [T1], 'key4': [V1]},
{'key1': [L2], 'key2': [P2], 'key3': [T1], 'key4': [V1]}

どんな援助でも!

4

3 に答える 3

1
In [1]: d = {'key1': ['L1', 'L2'],  
 'key2': ['P1', 'P2'],
 'key3': ['T1'],
 'key4': ['V1']}

In [2]: [{k: [v[min(i, len(v)-1)]] for k, v in d.items()}
     for i in range(max(map(len, d.values())))]
Out[2]: 
[{'key1': ['L1'], 'key2': ['P1'], 'key3': ['T1'], 'key4': ['V1']},
 {'key1': ['L2'], 'key2': ['P2'], 'key3': ['T1'], 'key4': ['V1']}]
于 2013-02-25T18:19:25.450 に答える
1
>>> # Let's suppose your dictionary looks something like
>>> some_dict = {'key1': ['L1', 'L2'],
 'key2': ['P1', 'P2'],
 'key3': ['T1'],
 'key4': ['V1']}
>>> #First determine the longest value sequence
>>> max_len = len(max(some_dict.values(), key = len))
>>> #assimilate your tools
>>> from itertools import izip, cycle, islice
>>> #Create the value sequence
>>> value = islice(izip(*(cycle(e) for e in some_dict.values())), max_len)
>>> #recreate the dictionary
>>> [dict(izip(some_dict.keys(), e)) for e in value]
[{'key3': 'T1', 'key2': 'P1', 'key1': 'L1', 'key4': 'V1'}, {'key3': 'T1', 'key2': 'P2', 'key1': 'L2', 'key4': 'V1'}]
>>> 

順序が重要な場合はOrderedDict、組み込みの dict の代わりにan を使用してください。

于 2013-02-25T18:29:34.443 に答える
0

['T1']または['V1']再度のコピーが必要な理由がわからないため、これはあなたが望んでいたものとまったく同じではありません。

d = {'key1': ['L1', 'L2'],
 'key2': ['P1', 'P2'],
 'key3': ['T1'],
 'key4': ['V1']}
print [{key:d[key][i] for key in d.keys() for i in range(len(d[key]))}, {key:d[key][i] for key in d.keys() for i in range(len(d[key])-1)}]

結果:

[{'key3': 'T1', 'key2': 'P2', 'key1': 'L2', 'key4': 'V1'}, {'key2': 'P1', 'key1': 'L1'}]
于 2013-02-25T18:31:49.507 に答える