擅长:python、mysql、java
<p>如果必须使用递归,那么可以将基本情况选择为空元组或第一个元素的键与<code>key</code>匹配的元组。在本例中,您将向最终结果追加一个更新的键。否则,通过保持第一个元素的原样并递归调用其余元素的<code>add_new</code>返回。你知道吗</p>
<p>这将产生以下功能:</p>
<pre><code>def add_new(t, key, value):
if len(t) == 0 or t[0][0] == key:
return ((key, value),) + t[1:]
return t[0:1] + add_new(t[1:], key, value)
tup = (('b', 2), ('a', 1), ('c', 3))
print(add_new(tup, "d", 4))
print(add_new(tup, "c", 9))
</code></pre>
<p><strong>输出</strong></p>
<pre><code>(('b', 2), ('a', 1), ('c', 3), ('d', 4))
(('b', 2), ('a', 1), ('c', 9))
</code></pre>