如何将列表元素作为变量返回?

1 投票
3 回答
1911 浏览
提问于 2025-04-18 05:49

我有一个复杂的变量,像下面这样...

test_list[[test1, test1_var1, test1,var2], [test2, test2_var1]]

我写了一个函数来提取我想要的测试中的变量,见下面...

def find_test(test_list, search_term):
    for index in range(len(test_list)):
        if test_list[index][0] == search_term:
            return test_list[index][1:]

这个函数返回的结果大概是这样的...

[test1_var1, test1_var2]

我希望能把这些变量单独返回,而不是作为列表中的元素。我要怎么做呢?怎么才能返回不确定数量的变量呢?(有点像 *args,但这是针对返回值,而不是参数)

3 个回答

0

只需使用内置的过滤功能,然后在你的函数调用中展开结果:

def search(haystack, needle):
    return filter(lambda x: x[0] == needle, haystack)[0][1:]

a,b = search(test_list, 'test1')

请记住,如果你的结果超过两个项目,上面的做法就会失败。

2

在Python中,返回多个变量其实就是返回一个可迭代的东西,所以返回一个列表和返回“多个变量”没有什么实际的区别:

def f():
    return 1,2
def g():
    return [1,2]
a,b=f()
c,d=g()

这两个函数唯一的区别是,f返回的是一个元组,而g返回的是一个列表——这没什么关系,因为如果你对返回的结果进行多重赋值的话,效果是一样的。

1

其实你可以通过使用列表来实现你想要的功能:

def find_test(test_list, search_term):
    for index in range(len(test_list)):
        if test_list[index][0] == search_term:
            return test_list[index][1:]

这里有一个解构数组的语法可以使用:

foo, bar = find_text(x, y)

如果你想把结果作为一个列表获取,你可以这样做:

l = find_text(x,y)

如果你只想获取一个元素:

foo, _ = find_text(x,y)
_, bar = find_text(x,y)

如果你喜欢阅读,这里有一些资源可以参考:

撰写回答