python将字符串转换为参数列表 [英] python convert a string to arguments list
本文介绍了python将字符串转换为参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以将字符串转换为python中的参数列表吗?
Can I convert a string to arguments list in python?
def func(**args):
for a in args:
print a, args[a]
func(a=2, b=3)
# I want the following work like above code
s='a=2, b=3'
func(s)
我知道:
列表可以只使用* list,但是list不能包含类似a = 2
list can, just use *list, but list can't have an element like: a=2
和eval只能计算表达式
and eval can only evaluate expression
这将是:
def func2(*args):
for a in args:
print a
list1=[1,2,3]
func2(*list1)
func2(*eval('1,2,3'))
推荐答案
您可以将输入的字符串压缩到字典中,然后使用它来调用函数,例如
You could massage the input string into a dictionary and then call your function with that, e.g.
>>> x='a=2, b=3'
>>> args = dict(e.split('=') for e in x.split(', '))
>>> f(**args)
a 2
b 3
这篇关于python将字符串转换为参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文