擅长:python、mysql、java
<p>您可以使用递归,然后测试实例是否是包含int值的简单元组,例如:</p>
<pre class="lang-py prettyprint-override"><code>sample = {(-1, 1): (0, 1),
(0, 0): [([([(1, 0), (0, 1)], (0, 1))], (1, 0))],
(0, 1): [([([((-1, 1), (0, 2))], (1, 1))], (0, 0))],
(0, 2): (0, 1)}
def flatten(data, output):
if isinstance(data, tuple) and isinstance(data[0], int):
output.append(data)
else:
for e in data:
flatten(e, output)
output = {}
for key, values in sample.items():
flatten_values = []
flatten(values, flatten_values)
output[key] = flatten_values
print(output)
>>> {(-1, 1): [(0, 1)], (0, 0): [(1, 0), (0, 1), (0, 1), (1, 0)], (0, 1): [(-1, 1), (0, 2), (1, 1), (0, 0)], (0, 2): [(0, 1)]}
</code></pre>