Skip to main content
 首页 » 编程设计

python之如何在具有各种数据类型的列表中搜索字符串,如果它们存在则对它们执行操作

2024年11月01日26zdz8207

我正在编写一个搜索方法,搜索不区分大小写。我可能正在搜索具有各种数据类型的列表/字典,如果列表中存在任何字符串,我该如何查询,对其执行类似 string.lower() 的操作?或者,我不知道这是否更省时,搜索列表中的所有字符串实例,并将它们添加到一个新集合中不区分大小写,然后在该集合中搜索我的字符串实例。

尝试了 any() 实现,但我认为我做错了,但也不确定这是执行我所描述的最有效的方法。

if isinstance(needle, str): #If needle is a string, convert it to lowercase and if haystack has any strings in it, convert them to lowercase too. 
            needle = needle.lower() 
 
            if any(str in haystack): 
 
                for item in haystack: 
 
                    if type(item) == str in haystack: 
                        item = item.lower() 

以上代码返回一个 TypeError: 'in <string>' requires string as left operand, not type. 我不太明白,因为我希望它能确定大海捞针中至少有一个字符串实例,然后对其执行 lower() 函数。

请您参考如下方法:

你可以试试:

my_list = [1, 2, 3, '1', 'A'] 
my_list = [e.lower() if isinstance(e, str) else e for e in my_list ] 

您可以应用任何适用于字符串的函数,而不是 lower 方法