循环函数来定义变量

循环函数来定义变量

问题描述:

我试着去创建一个函数,它接受一个列表,并指定每个字符串在列表中,即使你不知道有多少字符串列表中的一个变量循环函数来定义变量

下面是一些我尝试:

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]等即时通讯

的输出IM试图让:

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

我知道这个心不是做正确的方式,但我尝试以显示你们什么,我试图做

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

+2

首先,你不应该使用'list'作为变量名称 - 它在python中命名一个类型:-) – 2013-05-09 22:13:25

+1

你可以添加你期望得到的结果作为输出的问题吗? – 2013-05-09 22:14:05

+0

是的,你是正确的这只是一个例子 – Serial 2013-05-09 22:14:20

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

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' 
+0

我想它根本没用,但谢谢你回答我的问题! – Serial 2013-05-09 22:22:49

这够好吗?

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

print vars['a111'] 

如果你真的想要,然后你可以做

globals().update(vars) 

为输出IM试图让:

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和很多重复所有在这个网站(一)为什么你真不(b)如果你必须这样做,(c)即使你认为你必须这样做,你为什么不想这么做。

+0

不,我只是说在程序运行后,我可以使用这些变量来代表列表字符串 – Serial 2013-05-09 22:22:05

+0

,现在每个人都在说它的一个愚蠢的问题它的罚款我是一个初学者我没有,知道我知道了 – Serial 2013-05-09 22:23:47