定义变量的循环函数

2024-05-15 04:07:31 发布

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

我试图创建一个函数,它接受一个列表,并将列表中的每个字符串赋给一个变量,即使您不知道列表中有多少个字符串

以下是我尝试过的:

ExampleList = ['turtle','cow','goat','pig','swag']

def add_One(list):
    x = "a"+"1"
    y = 0
    y = y+1
    x = list[y]


while True:
    add_One(ExampleList)

所以基本上我以这个示例列表为例,然后我使用a1来定义ExampleList[1],然后我希望它循环并将a11分配给ExampleList[2]等等

对于我试图获得的输出:

a1 = ExampleList[1]
a11 = ExampleList[2]
a111 = ExampleList[3]
a1111 = ExampleList[4]

等等

我知道这不是正确的方法,但我想告诉你们我是怎么做的

如果有人知道如何正确地做到这一点,请帮助!你知道吗


Tags: 函数字符串add列表defa1onelist
3条回答

这够好吗?你知道吗

vars = {}
for i, value in enumerate(example_list, 1):
    vars['a' + '1'*i] = value

print vars['a111']

如果你真的想的话,你可以这样做

globals().update(vars)

我想这就是你想做的。我不知道你为什么要这么做,但你可以这样做:

example_list = ['turtle','cow','goat','pig','swag']
number_of_ones = 1
for item in example_list:
    globals()['a'+('1'*number_of_ones)] = item
    number_of_ones += 1

print(a11111) # prints 'swag'

如果希望它稍微短一点,请使用enumerate

example_list = ['turtle','cow','goat','pig','swag']
for number_of_ones, item in enumerate(example_list, 1):
    globals()['a'+('1'*i)] = item

print(a11111) # prints 'swag'

for an output im trying to get:

a1 = ExampleList[1]
a11 = ExampleList[2]
a111 = ExampleList[3]
a1111 = ExampleList[4]

如果您真的希望它作为输出,或者打印出来,或者作为字符串返回,那么这只是一个字符串格式问题,除了一个问题:您需要跟踪调用之间的一些持久状态。最好的方法就是用发电机,但如果你想的话,也可以直接做。例如:

def add_One(lst, accumulated_values=[0, "a"]):
    accumulated_values[0] += 1
    accumulated_values[1] += '1'
    print('{} = ExampleList[{}]'.format(*accumulated_values))

如果你的意思是要创建名为a1a11等的变量,请参阅Creating dynamically named variables from user input和这个站点上的许多重复项,了解(a)为什么你真的不想这么做,(b)如果必须怎么做,以及(c)为什么你真的不想这么做,尽管你认为必须这么做。你知道吗

相关问题 更多 >

    热门问题