使用Python中的map((函数映射列表后,如何访问列表?说如果我想重用这个列表,排序,以某种形式编辑它等等。
或者我的问题是,如何全局访问函数内部声明的变量?
我的代码在这里:
def list_mapper(number_string):
newlist = list(map(int, number_string.strip().split()))
list_mapper("4 5 4 5 4 5 43 ")
print(newlist)
但newlist
无法访问。这是正确的方法吗?还是应该以其他方式构建代码以便我访问它?
您已经在函数list_mapper
中创建了变量newlist
;这意味着它只能在函数内部使用。这是作用域的一个示例;在这种情况下,变量的作用域是函数的,在外部不可用。
通常的解决方案是让函数返回您想要使用的值。你可以这样做:
def list_mapper(number_string):
return list(map(int, number_string.strip().split()))
newlist = list_mapper("4 5 4 5 4 5 43 ")
print(newlist)
当你有一个函数时,你需要return
你希望它产生的值:
def list_mapper(number_string):
newlist = list(map(int, number_string.strip().split()))
return newlist
newlist = list_mapper("4 5 4 5 4 5 43 ")
print(newlist)
newlist在主区块中不存在(您应该有一个错误(您必须从list_mapper返回它,并使用主区块中的返回值
def list_mapper(number_string):
newlist = list(map(int, number_string.strip().split()))
return newlist
print(list_mapper("4 5 4 5 4 5 43 "))
您应该返回映射的列表。
def list_mapper(number_string):
newlist = list(map(int, number_string.strip().split()))
return newlist
newlist = list_mapper("4 5 4 5 4 5 43 ")
print(newlist)
通过使用return
,函数将返回列表,
def list_mapper(number_string):
newlist = list(map(int, number_string.strip().split()))
return newlist
lit=list_mapper("4 5 4 5 4 5 43 ")
print(lit)