如何从字符串列表中删除引号并将其再次存储为列表..?

问题描述

我必须在 for 循环中调用函数。所有这些函数都作为带引号的字符串存储在列表中。我需要删除这些引号并将值再次存储在列表中。

要做什么:

  1. 数据库获取函数列表
  2. 从字符串列表中删除单/双引号
  3. 将这些字符串存储在列表中
  4. 循环执行函数

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...