访问映射列表

2024-04-19 23:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用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无法访问。这是正确的方法吗?还是应该以其他方式构造代码以供我访问


Tags: 函数代码声明编辑numbermap列表string
3条回答

当你有一个函数时,你需要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)

您已经在函数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)

newlist在主组中不存在(您应该有一个错误) 您必须从列表映射器返回它,并在main bloc中使用返回值

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 "))

相关问题 更多 >