[英]How can I search an item in a list of lists?
I am doing a school project about a inventory system, and I am facing some problem in programming the Search
function. 我正在做一个有关库存系统的学校项目,在编写
Search
功能时遇到了一些问题。
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. 我想搜索
1
并希望显示包含1
的列表。
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] ) 您有一个嵌套列表,现在正在检查列表('1'与[1,2,3,4,5]不匹配)
so you have to loop over the list within the list and change input to int: 因此,您必须遍历列表中的列表,并将输入更改为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 ilist
是一个列表列表,您正在将search
与每个列表进行比较 int
, while search
is of type str
int
,而search
的类型是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
您可以使用
in
从每个list
查找元素
search = int(input('By user:'))
for item in ilist:
if search in item:
print(item)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.