我的python程序有问题。基本上,这是我正在尝试做的事情:
categories = [cat1 , cat2]
for x in categories:
print x
print function(x)
我想要它做的是打印这个:
CAT1
(当cat1变量用作参数时函数的结果)
CAT2
(你明白了)
答案 0 :(得分:1)
在此设置中,您的代码运行正常。你有什么问题吗?
>>> cat1 = "CAT1"
>>> cat2 = "CAT2"
>>>
>>> def function(x):
... return x[::-1]
...
>>> categories = [cat1, cat2]
>>>
>>> for x in categories:
... print x
... print function(x)
...
CAT1
1TAC
CAT2
2TAC
如果要打印cat1的名称,则必须以名称开头,因为引用和对象之间没有一对一的关系。
例如
categories = ["cat1", "cat2"]
for x in categories:
print x
print function(locals()[x])
答案 1 :(得分:0)
你走了:
#!/usr/bin/python
def myfunc(myvar):
return len(myvar)
cat1 = "First category"
cat2 = "Second category"
categories = [cat1, cat2]
variable_names = ["cat1", "cat2"]
for varname, category in zip(variable_names, categories):
print varname
print myfunc(category)
输出:
cat1
14
cat2
15
如果这真的是你想要的话,使用字典可能会更好:
#!/usr/bin/python
def myfunc(myvar):
return len(myvar)
categories = {"cat1": "First category", "cat2": "Second category"}
for category in categories:
print category
print myfunc(categories[category])