gpt4 book ai didi

python 列表 : double each element in a list while maintaining the structure

转载 作者:太空狗 更新时间:2023-10-30 02:28:36 25 4
gpt4 key购买 nike

如何编写一个函数来将列表中的每个元素加倍,同时保持列表的结构?

例如:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com