[英]How to remove quotes from list of strings and store it as list again..?
我必須在 for 循環中調用 function。 所有這些函數都作為帶引號的字符串存儲在列表中。 我需要刪除這些引號並將值再次存儲在列表中。
需要做什么:
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)()
Output
<class 'list'>
[apple,mango,orange]
<class 'str'>
從字符串中刪除引號后,其數據類型將更改為。 有沒有辦法從字符串列表中刪除引號並將這些值再次存儲為列表?
你不能調用這樣的函數。 從字符串中刪除引號不會將其變成 function。 您正在將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, mango, 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, mango, orange]'
構造這個列表,你需要eval
它:
s = '[apple, mango, orange]'
func = eval(s)
print(func)
結果是:
[<function apple at 0x000001FB9E7CF040>, <function mango at 0x000001FB9ECB7940>, <function orange at 0x000001FB9ECB7DC0>]
但是,如果可能的話,您應該始終盡量避免使用eval
根據您的代碼,我猜您想根據字符串調用 function 嗎? 我建議使用字典
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()
使用名稱獲取 function object 然后您可以使用該 object
func = [globals()[fun] for fun in fruits]
func_it = itertools.cycle(func)
for i in range(len(func)):
next(func_it)()
Output:
In apple
In mango
In orange
您可以使用內置的 python exec() function 將任何字符串作為代碼執行。
#!/usr/bin/env python3
fruits = ['apple','mango','orange']
def apple():
print("In apple")
def mango():
print("In mango")
def orange():
print("In orange")
for func in fruits:
exec(func + '()')
Output
In apple
In mango
In orange
在這里,行hehe = eval(func)
創建了一個名稱列表,稍后將其作為 function 調用,這是可能的,因為結束括號“()”不是必需的,至少在 Python 3.9 中。
import itertools
def apple():
print("In apple")
def mango():
print("In mango")
def orange():
print("In orange")
fruits = ['apple','mango','orange']
print(type(fruits))
func = '[%s]'%','.join(map(str,fruits))
print(func) ## [apple,mango,orange]
hehe = eval(func)
print(type(hehe))
n = len(hehe)
func_it = itertools.cycle(hehe)
for i in range(n):
next(func_it)()
output:
<class 'list'>
[apple,mango,orange]
<class 'list'>
In apple
In mango
In orange
fruits = '[apple, mango, orange]'
import json
fruits= json.loads(fruits)
output: fruits = [apple, mango, orange]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.