मुझे इस तरह के कोड की आवश्यकता है कि यदि एक निश्चित सूची सूचकांक मौजूद है, तो एक फ़ंक्शन चलाएं।
यह एक कोशिश ब्लॉक के लिए सही उपयोग है :
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...
हालाँकि, परिभाषा के अनुसार, पायथन सूची में सभी आइटम मौजूद हैं 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...
यदि आप कुछ परिभाषित 'सूचकांक' के बारे में सोच रहे हैं, तो मुझे लगता है कि आप गलत सवाल पूछ रहे हैं। शायद आपको एक मानचित्रण कंटेनर (जैसे एक तानाशाह) बनाम एक अनुक्रम कंटेनर (जैसे कि एक सूची) का उपयोग करने पर विचार करना चाहिए । आप अपने कोड को इस तरह दोबारा लिख सकते हैं:
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एक पूर्णांक के रूप में कास्ट लिखना चाहते हैं , सूची नहीं। मैं उलझन में हूं।