[英]In Python, I am having trouble finding out if an item is in a list
我正在尝试在嵌套列表中搜索项目。 列表将混合字符串和数字......我想它们不一定是整数。 与我正在尝试编写的程序分开,我编写了一小部分代码只是为了玩弄搜索列表,但似乎没有任何效果。 我是新手,所以对我很轻松。 我很欣赏这里的任何方向。 列表打印的内容和用户输入部分的变量确实设置得当。 但是,当我期望“True”时,我得到“False”,而我试图查看该项目是否存在的“if”语句一直告诉我它不存在。
这是我的测试文件的代码:
test_list=[['a','b','c',1,2,3],['d','e','f',4,5,6]]
print('contents of the list:')
print (test_list)
print('Checking if "a" is in the list:')
if ('a' in test_list)==True:
print('yes its in the list')
else:
print('no it is not in the list')
print('')
print('will this return True?:')
print('a' in test_list)
# trying a user entered value, which
# is directly related to what I want to do
print('now for a user entered value:')
item=input ('enter-->')
if ((item) in test_list)==True:
print('yes its in the list')
else:
print('no it is not in the list')
print('')
# shows the user's entry, to show that at least
# the 'item' variable had been set to the value.
# This does show the value entered.
print('The entered number was',item)
print ((item) in test_list)
再次感谢!
对于“深度”递归搜索(不仅在第一级),您可以使用如下递归函数:
def search_recursive(el, l):
if el in l:
return True
for e in l:
if type(e) == list:
return search_recursive(el, e)
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.