#範例4-5:查詢元素是否在串列list內: #☎方法1:一般一維串列:if txt in a a=['tom','mike','peter','yellow'] def find_tuple(txt,a): if txt in a: return txt + '存在list內' else: return txt + '不存在list內' s = input('請輸入查詢姓名?') res = find_tuple(s,a) print(res) #☎方法2:一般一維串列:a.index(txt) #[1,2,3].index(2) # => 1 #[1,2,3].index(4) # => ValueError a=['tom','mike','peter','yellow'] s = input('請輸入查詢姓名?') try: res = a.index(s) print(s+'找到了,在編號為'+str(res)+'的位置') except ValueError: print(s+'找不到') #☎方法3:一般一維串列:[x+'找到了' for i,x in enumerate(a) if s==x] a=['tom','mike','peter','yellow'] s = input('請輸入查詢姓名?') #查詢方法1: print([x+'找到了' for i,x in enumerate(a) if s==x]) #☎方法4:一般一維串列:for i,x in enumerate(a) if s==x a=['tom','mike','peter','yellow'] s = input('請輸入查詢姓名?') #查詢元素方法: b = ['姓名為'+x for i,x in enumerate(a) if s==x] if b==[]: print('找不到') else: print(b)