简体   繁体   English

如何检查列表中是否存在 integer 或字符串

[英]How to check if an integer or string exists in a list

I want to know how I can check if an integer is in a list.我想知道如何检查 integer 是否在列表中。 Here is some code I made:这是我制作的一些代码:

# "1" is a string. 10 is an integer.
my_list = ["1", 10]
if int in my_list:
    print("Integer in the list!")

What is wrong with this code?这段代码有什么问题? And how do I make it work?我如何让它发挥作用?

As mentioned by Cargcigenicate, both int == "1" and int == 10 are False , so the overall check is False .正如 Cargcigenicate 所提到的, int == "1"int == 10都是False ,所以整体检查是False What you want to do is check whether or not an element in the list is an instance of int , not whether or not they are equal to int .您要做的是检查列表中的元素是否是int实例,而不是它们是否等于int

This can be accomplished a bit more concisely by using the builtin any along with a generator expression :这可以通过使用内置的any生成器表达式来更简洁地完成:

if any(isinstance(x, int) for x in my_list):
    ...

Note that in general using isinstance should be prefered over type when reasoning about the type of an object since the former takes inheritance into account.请注意,在推理 object 的type时,通常应该优先使用isinstance而不是 type ,因为前者考虑了 inheritance。

The problem with this is, int == 10 is false.问题是int == 10是错误的。 int is a class, and 10 is an instance of the class. int是 class, 10是 class 的实例。 That doesn't mean however that they equate to each other.然而,这并不意味着它们彼此等同。

You'd need to do some preprocessing first.您需要先进行一些预处理。 There's many ways to do this, and it ultimately depends on what your end goal is, but as an example:有很多方法可以做到这一点,最终取决于你的最终目标是什么,但作为一个例子:

my_list = ["1", 10]

# Create a new list that holds the type of each element in my_list
types = [type(x) for x in my_list]

if int in types:  # And check against the types, not the instances themselves
    print("Integer in the list!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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