擅长:python、mysql、java
<p>我假设您想将名称放入dict值中,替换空字符串。在这种情况下,我会把你最初的字典扔掉,这样做:</p>
<pre><code>from itertools import count
def generate(lst):
target = {}
for index in count(1):
target[index] = {}
for subindex in xrange(1, 4):
target[index][subindex] = lst.pop()
if not lst:
return target
generate(['Erich Martin', 'Zia Michael', 'Olga Williams', 'Uma Gates'])
</code></pre>
<p>或者更优雅</p>
<pre><code>from itertools import izip_longest
def generate(lst):
groups = izip_longest(fillvalue='', *([iter(lst)] * 3))
dictgroups = [dict(enumerate(group, 1)) for group in groups]
return dict(enumerate(dictgroups, 1))
generate(['Erich Martin', 'Zia Michael', 'Olga Williams', 'Uma Gates'])
</code></pre>
<p>这两种解决方案都适用于任何输入列表,没有对长度的限制,就像对现有dict进行变异一样</p>