如何检查Python列表是否包含任何字符串作为元素

问题描述 投票:0回答:4

因此,我正在开发一个 Python 函数,该函数接收数字列表作为参数并对其进行处理,就像这个示例一样:

def has_string(myList: list) -> str:

    # Side cases
    if myList == []:
        return "List shouldn't be empty"

    if myList contains any str object:  # Here's the problem
        return "List contains at least one 'str' object"

    return "List contains only numeric values"

我尝试过一些方法,例如:

  1.  if str in my_list:  # return message
    
  2.  if "" in my_list:  # return message
    
  3.  if my_list.count(""):  # return message
    

我不想创建一个

for
循环并一项一项地检查每一项。我想避免只是为了判断我的列表是否包含字符串而遍历所有项目。

正如我之前提到的,我尝试了一些不同的方法来在

if
块内检查它,但没有一个起作用。即使有条件停止,程序仍然继续处理列表。

非常感谢任何帮助,提前致谢!

python string list any
4个回答
5
投票

all()
在第一个值为 False 的项目处停止。基本上:

if all(isinstance(x, (int, float)) for x in my_list):
    print("all numbers!")
else:
    print("not all number!")

使用这些 C 级函数而不是推导式应该会更高效:

from itertools import repeat
if all(map(isinstance, my_list, repeat((int, float)))):
    print("all numbers!")
else:
    print("not all number!")

1
投票

除了检查序列之外,我想不出任何其他方法来检查序列,无论是使用

for
循环显式执行,还是使用更高级别的构造隐式执行。鉴于此,如果您的意图是在如上所述的列表中找到非数字值时“结束程序”,您可能会考虑这样的事情。

示例:

my_list = [1,2,3,4,6,7,"8"]

for value in my_list:
    if not isinstance(value, (int, float)):
        raise TypeError(f"Expected only numeric types, found {type(value)} in sequence.")

输出:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-791ea7c7a43e> in <module>
      3 for value in my_list:
      4     if not isinstance(value, (int, float)):
----> 5         raise TypeError(f"Expected only numeric types, found {type(value)} in sequence.")

TypeError: Expected only numeric types, found <class 'str'> in sequence.

1
投票

由于您不想

for
循环使用
map
并获取列表中每个元素的类型,那么您可以使用
in
来检查列表是否包含字符串:

seq = [0, 1, 2, 3, 4, "Hello"]

if str in map(type, seq):
    print("List contains string")

else:
    print("Accepted")

0
投票
seq = [0, 1, 2, 3, "5", 8, 13] 

result = filter(lambda x: type(x)==str, seq)
 
print(list(result))

这段代码可能会过滤列表中的所有 str 类型值

© www.soinside.com 2019 - 2024. All rights reserved.