循环函数来定义变量
我试着去创建一个函数,它接受一个列表,并指定每个字符串在列表中,即使你不知道有多少字符串列表中的一个变量循环函数来定义变量
下面是一些我尝试:
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]
等即时通讯
的输出IM试图让:
a1 = ExampleList[1]
a11 = ExampleList[2]
a111 = ExampleList[3]
a1111 = ExampleList[4]
等
我知道这个心不是做正确的方式,但我尝试以显示你们什么,我试图做
如果有人知道如何正确地做到这一点,请帮助!
我认为这是你想要做的。我不知道为什么地球上你想这样做,但你可以做这样的:
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'
我想它根本没用,但谢谢你回答我的问题! – 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))
如果你的意思是你想创建一个名为a1
,a11
等变量,看Creating dynamically named variables from user input和很多重复所有在这个网站(一)为什么你真不(b)如果你必须这样做,(c)即使你认为你必须这样做,你为什么不想这么做。
首先,你不应该使用'list'作为变量名称 - 它在python中命名一个类型:-) – 2013-05-09 22:13:25
你可以添加你期望得到的结果作为输出的问题吗? – 2013-05-09 22:14:05
是的,你是正确的这只是一个例子 – Serial 2013-05-09 22:14:20