作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如何编写一个函数来将列表中的每个元素加倍,同时保持列表的结构?
例如:
f([1, [2, [3]]]) => [2, [4, [6]]]
最佳答案
一个简单的方法可能是:
def double(li):
try:
return [double(x) for x in li]
except: # li is not iterable, recursion base case
return 2*li # or sth. else for non-numerical, non-iterable types
但是请注意,此解决方案“列出”了所有类型的可迭代对象。维护可迭代对象类型的更复杂版本,因此可以处理列表、元组、集合等的任何嵌套结构,将在 try block 中包含以下行:
return type(li)(map(double, li)) # should work in Python 2 and 3
这会实例化并返回 li
的原始类型(列表、元组等)的对象,其中包含 中所有双重元素的列表 (Py2) 或映射对象 (Py3) >li
.
关于 python 列表 : double each element in a list while maintaining the structure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242316/
我是一名优秀的程序员,十分优秀!