ฉันต้องเขียนโค้ดเพื่อให้ถ้าดัชนีรายการมีอยู่ให้เรียกใช้ฟังก์ชัน
นี่คือการใช้งานที่สมบูรณ์แบบสำหรับการลองบล็อก :
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
มีอยู่ (กล่าวคือไม่จำเป็นต้องลองยกเว้นถ้าคุณรู้0 <= index < len(the_list)
)
คุณสามารถใช้การแจงนับได้หากคุณต้องการให้ดัชนีอยู่ระหว่าง 0 ถึงองค์ประกอบสุดท้าย:
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แทนที่จะลอง / ยกเว้นเวอร์ชันที่สั้นกว่า:
>>> something_to_do.get(3, default)('bob')
some thing 1 done with bob
>>> something_to_do.get(22, default)('alice')
nothing done with alice
n
เป็นจำนวนเต็มไม่ใช่รายการ ฉันสับสน