繁体   English   中英

在 Python 中,我无法确定某个项目是否在列表中

[英]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)

再次感谢!

if item in test_list test_list 中的项目为False ,因为test_list是列表列表,并且您只搜索第一个“级别”。 使用列表推导搜索嵌套列表:

if [item in sublist for sublist in test_list]:
    print("Found!")

另外,请记住input()总是返回一个str ,因此您将无法搜索您的数字列表成员,除非您将其转换为int ,或者将所有列表项转换为字符串。

对于“深度”递归搜索(不仅在第一级),您可以使用如下递归函数:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM