Return 列表的名称,如果它包含所需的值 (Python)
Return the name of a list if it contain the needed value (Python)
我正在尝试获取包含所需值的列表(类型列表)的名称:
def f(Value):
a = ['a','b','c']
b = ['d','e','f']
d = ['g','h','i']
c = ['j','k','l']
w = next(n for n,v in filter(lambda t: isinstance(t[1],list), locals().items()) if value in v)
return(w)
f()
好吧,此代码将 return 列表的名称但键入字符串,因此我以后将无法使用它。提前谢谢你
您的代码中有几个错误 - 如果您想要列表,那么 return 它而不是它的名称:
def f(value): # capitalization not correct
a = ['a','b','c']
b = ['d','e','f']
d = ['g','h','i']
c = ['j','k','l']
# set w to v not n - n is the local name, v is the value
w = next(v for n,v in filter(lambda t: isinstance(t[1],list),
locals().items()) if value in v)
return w
# needs to be called with parameter
what_list = f("h")
print( what_list )
输出:
['g', 'h', 'i']
我不明白为什么要在这个最小的例子中使用 locals().items()
,你可以这样做
for li in [a,b,c,d]: # simply add more lists if needed, no need to inspect locals
if value in li:
return li
相反。
我正在尝试获取包含所需值的列表(类型列表)的名称:
def f(Value):
a = ['a','b','c']
b = ['d','e','f']
d = ['g','h','i']
c = ['j','k','l']
w = next(n for n,v in filter(lambda t: isinstance(t[1],list), locals().items()) if value in v)
return(w)
f()
好吧,此代码将 return 列表的名称但键入字符串,因此我以后将无法使用它。提前谢谢你
您的代码中有几个错误 - 如果您想要列表,那么 return 它而不是它的名称:
def f(value): # capitalization not correct
a = ['a','b','c']
b = ['d','e','f']
d = ['g','h','i']
c = ['j','k','l']
# set w to v not n - n is the local name, v is the value
w = next(v for n,v in filter(lambda t: isinstance(t[1],list),
locals().items()) if value in v)
return w
# needs to be called with parameter
what_list = f("h")
print( what_list )
输出:
['g', 'h', 'i']
我不明白为什么要在这个最小的例子中使用 locals().items()
,你可以这样做
for li in [a,b,c,d]: # simply add more lists if needed, no need to inspect locals
if value in li:
return li
相反。