简体   繁体   English

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

[英]In Python, I am having trouble finding out if an item is in a list

I am trying to search nested lists for items.我正在尝试在嵌套列表中搜索项目。 The lists will have a mixture of strings and numbers...which don't have to be integers I suppose.列表将混合字符串和数字......我想它们不一定是整数。 Separate from the program I am trying to write, I made a small set of code just to play around with searching lists, but nothing seems to work.与我正在尝试编写的程序分开,我编写了一小部分代码只是为了玩弄搜索列表,但似乎没有任何效果。 I am new to this so be easy on me.我是新手,所以对我很轻松。 I appreciate any direction here.我很欣赏这里的任何方向。 The contents of the list print, and the variable for the user input section does set appropriately.列表打印的内容和用户输入部分的变量确实设置得当。 However, I am getting "False" when I would expect "True", and my 'if' statements that try to see if the item exists keeps telling me that it does not.但是,当我期望“True”时,我得到“False”,而我试图查看该项目是否存在的“if”语句一直告诉我它不存在。

Here is the code of my test file:这是我的测试文件的代码:

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)

Thanks again!再次感谢!

You are getting False for if item in test_list because test_list is a list of lists, and you are only searching the first "level". if item in test_list test_list 中的项目为False ,因为test_list是列表列表,并且您只搜索第一个“级别”。 Use a list comprehension to search nested lists:使用列表推导搜索嵌套列表:

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

Also, keep in mind that input() always returns a str , so you won't be able to search your numeric list members unless you cast it to an int , or turn all the list items into strings.另外,请记住input()总是返回一个str ,因此您将无法搜索您的数字列表成员,除非您将其转换为int ,或者将所有列表项转换为字符串。

For a recursive search "in depth" (not only at the first level) you can use a recursive function like this:对于“深度”递归搜索(不仅在第一级),您可以使用如下递归函数:

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