简体   繁体   English

如何在python中检查混合类型列表中是否有字符串项目

[英]How do I check if there is a string item in a list of mixed types, in python

Say I have a list l1 = ['s',1,2] and l2 = [1,2,3] . 假设我有一个list l1 = ['s',1,2] and l2 = [1,2,3] Obviously l1 has an item of string type and l2 doesn't. 显然, l1有一个字符串类型的项,而l2没有。

But when a list gets super large and I do not know the items in a list, how do I know if this list contains an item of string type. 但是,当列表变得非常大而我不知道列表中的项目时,如何知道该列表是否包含字符串类型的项目。

if any(isinstance(x, str) for x in your_list):
    print("the list contains a string")

You can use a loop and check if, at each index of your array, the value is corresponding to a number. 您可以使用循环并检查数组的每个索引处的值是否对应于一个数字。 Use ascii code ( code 48 to 57 for 0 to 9) If the ascii code of your value is between 48 and 57, you know it's a number. 使用ASCII码(0到9的代码是48到57)如果您的值的ASCII码在48到57之间,则您知道它是一个数字。 If not, you know it's not a number. 如果不是,您知道它不是数字。

Hope this helps 希望这可以帮助

I just saw this post : What's the canonical way to check for type in python? 我刚刚看到了这篇文章: 检查python类型的规范方法是什么?

quote : "Since Python encourages Duck Typing, you should just try to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file, just try to use its .write() method!" quote“由于Python鼓励使用Duck Typing,所以您应该尝试以想要使用它们的方式使用对象的方法。因此,如果您的函数正在寻找可写文件对象,请不要检查它是否是文件的子类,尝试使用其.write()方法!” (This answer were quite suprising to me) (这个答案令我惊讶)

The way i understood that is that you have to act like if all your items in your list were like you want (we don't know yet what do you want to do with your lists). 我的理解是,如果列表中的所有项目都像您想要的那样,您必须采取行动(我们尚不知道您想对列表做些什么)。

您可以尝试以下方法:

if any(type(each_item) is str for each_item in l1): # Do something

The solution using isinstance function: 使用isinstance函数的解决方案:

def hasString(l):
    for item in l:
        if isinstance(item, str):
            return True
    return False

l1 = [1, 2, 3]
l2 = ['s', 2, 3]

print(hasString(l1))  # False
print(hasString(l2))  # True

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

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