我需要编写这样的代码,如果存在某个列表索引,则运行一个函数。
这是try 块的完美用途:
ar=[1,2,3]
try:
t=ar[5]
except IndexError:
print('sorry, no 5')
# Note: this only is a valid test in this context
# with absolute (ie, positive) index
# a relative index is only showing you that a value can be returned
# from that relative index from the end of the list...
但是,根据定义,Python 列表中的所有项目都存在于0
和之间len(the_list)-1
(即,如果您知道,则不需要 try 块0 <= index < len(the_list)
)。
如果你想要 0 和最后一个元素之间的索引,你可以使用enumerate :
names=['barney','fred','dino']
for i, name in enumerate(names):
print(i + ' ' + name)
if i in (3,4):
# do your thing with the index 'i' or value 'name' for each item...
但是,如果您正在寻找一些已定义的“索引”,我认为您问的是错误的问题。也许您应该考虑使用映射容器(例如 dict)与序列容器(例如列表)。你可以像这样重写你的代码:
def do_something(name):
print('some thing 1 done with ' + name)
def do_something_else(name):
print('something 2 done with ' + name)
def default(name):
print('nothing done with ' + name)
something_to_do={
3: do_something,
4: do_something_else
}
n = input ("Define number of actors: ")
count = 0
names = []
for count in range(n):
print("Define name for actor {}:".format(count+1))
name = raw_input ()
names.append(name)
for name in names:
try:
something_to_do[len(name)](name)
except KeyError:
default(name)
像这样运行:
Define number of actors: 3
Define name for actor 1: bob
Define name for actor 2: tony
Define name for actor 3: alice
some thing 1 done with bob
something 2 done with tony
nothing done with alice
您也可以使用.get方法而不是 try/except 更短的版本:
>>> something_to_do.get(3, default)('bob')
some thing 1 done with bob
>>> something_to_do.get(22, default)('alice')
nothing done with alice