我必须处理列表或列表列表。我发现我目前的方法不是很有效,因为我必须定义两个单独的方法来做事,并有效地将它们写出来两次。有没有更有效的方法来检查传入数据是列表还是列表列表,然后相应地继续(我通常希望对每个传入数据项进行操作,并输出与传入数据结构匹配的列表或列表列表(。这是我处理它的一个例子:
if not any(isinstance(item, list) for item in keys):
userStrings = []
for key in keys[index]:
userStrings[index].extend(item.GetUserStrings().GetValues(key))
else:
userStrings = [[] for i in range(len(rhObjects))]
for index, item in enumerate(rhObjects):
for key in keys[index]:
userStrings[index].extend(item.GetUserStrings().GetValues(key))
如果我遇到更复杂的事情,它是列表列表等,该怎么办。此方法将不起作用...想法?
谢谢!
这似乎还不够清楚。让我们重新开始。想象一下,我有一个列表列表,一个列表,甚至一个对象列表列表的列表:
_list = [["X","Y","Z"],["X","Y","Z",["X","Y","Z"]],["X","Y","Z"]]
_list2 = ["X","Y","Z"]
_list3 = [["X","Y","Z"],["X","Y","Z"]]
我想做的只是对这些列表中的每个对象执行一个简单的功能(将"A"附加到每个对象(或创建一个全新的对象,但以与原始输入列表的结构相匹配的方式。示例函数:
def my_function(obj):
return obj + "A"
def my_function2(obj):
return newObj
期望输出:
_newList = [["XA","YA","ZA"],["XA","YA","ZA",["XA","YA","ZA"]],["XA","YA","ZA"]]
_newList2 = ["XA","YA","ZA"]
_newList3 = [["XA","YA","ZA"],["XA","YA","ZA"]]
或者,如果使用my_function2:
_newList = [["newObj","newObj","newObj"],["newObj","newObj","newObj",["newObj","newObj","newObj"]],["newObj","newObj","newObj"]]
有没有办法像下面用户建议的两个功能一样?一个递归?我完全是递归的菜鸟,您在顶部看到的第一种方法是我检查列表中列表的方式,但它真的不灵活。感谢所有/任何帮助!
你的逻辑应该在一个单独的方法中,你应该使用递归。
def process_list(_list):
new_list = []
for x in _list:
if is_list(x):
new_list.append(process_list(x))
else:
new_list.append(map(lambda y: y + "A",x))
return new_list
def is_list(l):
return type(l) == types.ListType
_list = [["X","Y","Z"],["X","Y","Z",["X","Y","Z"]],["X","Y","Z"]]
print(process_list(_list))
print(_list)
代码只是为了演示递归。希望你得到它并同样构建你的代码。