Python:如何为每个x使用x编写?

ren*_*ndy 1 python

#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
Run Code Online (Sandbox Code Playgroud)

是否有一种自动方式让python读取每行的第一部分?而不是做上述?我试图在每一行上使用第一个str char作为python识别下一个动作的方式.

Ash*_*ary 6

您可以创建一个字典和地图'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]]()
Run Code Online (Sandbox Code Playgroud)

输出:

func1
func2
func3
Run Code Online (Sandbox Code Playgroud)