Python使用def函数创建不同的变量

时间:2018-07-27 02:14:06

标签: python python-3.x function

我是python的新手,只想问一下是否可以使用def函数创建新变量。

这是我的代码,尝试构建一个可以输入变量名称和数据的函数,它将自动输出其他列表。但它似乎不起作用:

def Length5_list(list_name, a, b, c, d, e):
    list_name = list()
    list_name = [a, b, c, d, e]

list_name1 = 'first_list'
list_name2 = 'second_list'
A = 1
B = 2
C = 3
D = 4
E = 5

Length5_list(list_name1, A, B, C, D, E)
Length5_list(list_name2, E, D, C, B, A)

print(list_name1, list_name2)

还想知道是否还有其他方法可以实现?

非常感谢你们!

1 个答案:

答案 0 :(得分:1)

不要动态命名变量。而是使用字典并使用项目进行更新。然后通过d[key]检索列表,其中key是您提供给函数的字符串。

这是一个例子:

def lister(list_name, a, b, c, d, e):
    return {list_name: [a, b, c, d, e]}

list_name1 = 'first_list'
list_name2 = 'second_list'
A, B, C, D, E = range(1, 6)

d = {}

d.update(lister(list_name1, A, B, C, D, E))
d.update(lister(list_name2, E, D, C, B, A))

print(d['first_list'], d['second_list'], sep='\n')

[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

虽然可能存在动态创建变量的方法,但不建议这样做。有关更多详细信息,请参见How do I create a variable number of variables?

相关问题