Python:如何为每个x使用x写?
问题描述:
#python
list="""a 1 2 3 4 5
b 1 2 3 4 5
c 1 2 3 4 5 """
a=list.split('\n')
if a[0][0]==a:
do something
if a[1][0]==b:
do something
if a[2][0]==c:
do something
是否有自动的方式让python读取每行的第一部分?而不是做以上?我试图使用每行上的第一个str字符作为python识别下一个动作的方式。Python:如何为每个x使用x写?
答
您可以创建一个字典和地图'a'
,'b'
,'c'
一些功能:
def func1(): print "func1"
def func2(): print "func2"
def func3(): print "func3"
dic={"a":func1,"b":func2,"c":func3}
lis="""a 1 2 3 4 5
b 1 2 3 4 5
c 1 2 3 4 5 """
for item in lis.splitlines():
dic[item[0]]()
输出:
func1
func2
func3
答
你当然可以使用哈希映射名称动作:
actions = { "a": do_a, "b": do_b, "c": do c }
for l in list.splitlines():
here = l[0]
if here in actions:
actions[here]()
答
map(lambda xs: if xs[0] == a: dosomething, list.split('\n'))
可能是你在找什么。
+0
-1试试你的代码,看看它是否先工作 – jamylak 2013-05-03 12:50:50
谢谢sashkello切片帮助! – rendy 2013-05-03 11:57:30
不要命名一个变量'list'。 *特别是*不是一个列表。 – geoffspear 2013-05-03 12:03:41