0

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

这是我尝试过的东西:

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]然后我希望它循环并分配a11ExampleList[2]等等

对于我试图获得的输出:

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

等等

我知道这不是正确的方法,但我试图向你们展示我正在尝试做的事情

如果有人知道如何正确执行此操作,请提供帮助!

4

3 回答 3

3

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

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'
于 2013-05-09T22:19:18.583 回答
2

这够好吗?

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

print vars['a111']

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

globals().update(vars)
于 2013-05-09T22:19:19.553 回答
1

对于我试图获得的输出:

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

如果您的意思是您正在尝试创建名为a1,a11等的变量,请参阅从用户输入创建动态命名变量以及本网站上的许多重复项,了解 (a) 为什么您真的不想这样做,(b ) 如果你必须怎么做,以及 (c) 为什么你真的不想这样做,即使你认为你必须这样做。

于 2013-05-09T22:20:54.403 回答