Elemento indekso paieška pagal jo reikšmę Python
Jei mums reikia rasti elementą sąraše ir
gauti jo indeksą, mes taikome
metodą index. Į pirmą parametrą
perduodame elemento reikšmę. Antrame ir
trečiame neprivalomuose parametruose galime
nurodyti paieškos pradžią ir pabaigą atitinkamai.
Suraskime 1 indeksą iš mūsų
sąrašo:
lst = [1, 2, 3]
print(lst.index(1)) # išves 0
Dabar nustatykime paieškos pradžią ir pabaigą elementui:
lst = [1, 2, 3, 1, 4]
print(lst.index(1, 2, 4)) # išves 3
Jei elemento nėra sąraše, metodas index
grąžins klaidą:
lst = [1, 2, 3]
print(lst.index(4)) # išves klaidą
Duotas sąrašas:
lst = ['a', 'b', 'c', 'd', 'e']
Raskite elemento su reikšme
'c' numerį.
Duotas sąrašas:
lst = ['a', 'b', 'c', 'b', 'd']
Raskite antrojo elemento su reikšme
'b' numerį.
Duotas toks kodas:
lst = ['ab', 12, 'cd', 34]
tst = 'cd'
print(lst.index(tst))
Pasakykite, kas išves į konsolę.
Duotas toks kodas:
lst = [1, 3, 'a', 'b', 3, 6]
tst = 2
print(lst.index(tst))
Pasakykite, kas išves į konsolę.