![](/img/trans.png)
[英]Recursive function to flatten any list in Python (2.7) is not working
[英]Flatten list from recursive function in Python
我正试图找到一种方法来展平我的列表,以便输出:
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
到目前为止,我的递归函数返回一个新的嵌套值列表,其中字典中的匹配键(使用旧参数列表和字典)如下所示:
l = ['won', 'too', 'three', 'fore', 'five', 'six', 'seven', 'ate', 'nein']
d = dict(won='one', too='two', fore='four', ate='eight', nein='nine')
def subst(l,d):
if len(l) == 1:
if l[0] in d:
return d[l[0]]
else:
return l[0]
else:
return [d[l[0]] if l[0] in d else l[0]] + [subst(l[1:],d)]
到目前为止,我一直在:
['one', ['two', ['three', ['four', ['five', ['six', ['seven', ['eight', 'nine']]]]]]]]
有没有什么办法可以在保持函数的递归完整性的同时展平列表?
您可以省略递归subst()
调用周围的[]
。
或者,你可以做到
def subst(l, d):
return [d.get(i, i) for i in l]
它只是迭代列表并用d
的相应条目替换每个项目(如果有的话),创建一个包含结果的新列表。
如果你想保留清单,你可以这样做
def subst(l, d):
for n, i in enumerate(l):
l[n] = d.get(i, i)
在同时删除的答案中, 有人询问 [d[x] for x in l if x in d]
的竞争条件, [d[x] for x in l if x in d]
。
争用条件-在某个线程程序的情况下-包括之间的分离的if x in d
和d[x]
的访问。 如果另一个线程正确删除了d
引用的dict中的那个条目,则测试成功,但访问仍然失败。
map(lambda x: d[x] if x in d else x,l)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.