问题描述
我必须在 for 循环中调用该函数。所有这些函数都作为带引号的字符串存储在列表中。我需要删除这些引号并将值再次存储在列表中。
需要做什么:
Python
fruits = ['apple','mango','orange']
print(type(fruits))
func = '[%s]'%','.join(map(str,fruits))
print(func) ## [apple,mango,orange]
print(type(func))
def apple():
print("In apple")
def mango():
print("In mango")
def orange():
print("In orange")
n = len(func)
func_it = itertools.cycle(func)
for i in range(n):
next(func_it)()
<class 'list'>
[apple,orange]
<class 'str'>
从字符串中删除引号后,其数据类型将更改为 . 有没有办法从字符串列表中删除引号并将这些值再次存储为列表?
解决方法
你不能这样调用函数。从字符串中删除引号不会将其转换为函数。您正在将 func
构造为 '[apple,mango,orange]'
,这是一个字符串。当您迭代时,您将获得字符串的每个字符。即你得到 [
、a
等。每个都是一个字符串,你不能调用字符串。你基本上是在做 '['()
,这是毫无意义的。
记住 - 在 Python 中 - 函数是一流的对象。如果您想列出函数,只需将这些函数的引用放在列表中:
import itertools
def apple():
print("In apple")
def mango():
print("In mango")
def orange():
print("In orange")
func = [apple,orange] # list of functions
n = len(func)
func_it = itertools.cycle(func)
for i in range(n):
x = next(func_it)
print(type(x)) # check the type
x()
结果:
<class 'function'>
In apple
<class 'function'>
In mango
<class 'function'>
In orange
所以如果你想从你的字符串 '[apple,orange]'
构建这个列表,你需要 eval
它:
s = '[apple,orange]'
func = eval(s)
print(func)
结果:
[<function apple at 0x000001FB9E7CF040>,<function mango at 0x000001FB9ECB7940>,<function orange at 0x000001FB9ECB7DC0>]
但是,如果可能,您应该始终尽量避免使用 eval
根据您的代码,我猜您想根据字符串调用函数?我建议使用字典
import itertools
fruits = ['apple','mango','orange']
def apple():
print("In apple")
def mango():
print("In mango")
def orange():
print("In orange")
funcs = {'apple':apple()}
funcs['apple']
出
In apple
,
您可以使用 globals()
获取使用名称的函数对象,然后您可以使用该对象
func = [globals()[fun] for fun in fruits]
func_it = itertools.cycle(func)
for i in range(len(func)):
next(func_it)()
输出:
In apple
In mango
In orange
,
您可以使用内置的 python exec() 函数将任何字符串作为代码执行。
#!/usr/bin/env python3
fruits = ['apple','orange']
def apple():
print("In apple")
def mango():
print("In mango")
def orange():
print("In orange")
for func in fruits:
exec(func + '()')
输出
In apple
In mango
In orange