I am doing a school project about a inventory system, and I am facing some problem in programming the Search
function.
Take an example:
ilist = [ [1,2,3,4,5], [6,7,8,9,10], [...], ...]
I would like to search for 1
and want the list containing 1
to display.
search = input('By user:')
for item in ilist:
if item == search :
print(item)
It does not work this way and I get this error:
list index out of range error
you have a nested list and are now checking against the list ('1' wont match with [1,2,3,4,5] )
so you have to loop over the list within the list and change input to int:
ilist = [ [1,2,3,4,5], [6,7,8,9,10]]
search = input('By user:')
for item in ilist:
for i in item:
if i == int(search):
print(i)
this is building on your way of coding, could be further improved from this
Two problems:
ilist
is a list of lists, and you're comparing search
to each list int
, while search
is of type str
In short, change this:
if item == search
To this:
if int(search) in item
You can use in
to find the element from each list
search = int(input('By user:'))
for item in ilist:
if search in item:
print(item)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.