Python 如何检查子列表中的元素是否为字符串?
我知道上面的代码返回false,因为列表中的元素都是列表。如果它始终是一个二维列表,那么您可以在Python 如何检查子列表中的元素是否为字符串?,python,list,Python,List,我知道上面的代码返回false,因为列表中的元素都是列表。如果它始终是一个二维列表,那么您可以在all()中的理解中使用第二个: (注意:我用justall()替换if all(…):True;else False,因为all()返回True或False答案) 你的条件isinstance(e,str)可以是你想要的任何东西-你的问题标题说你想检查它们是否是整数,如果是这种情况,你可以将条件更改为e.isdigit(),如果字符串表示整数,则返回True,否则返回False。您正在迭代数组[“a
all()中的理解中使用第二个:
(注意:我用justall()
替换if all(…):True;else False
,因为all()
返回True
或False
答案)
你的条件isinstance(e,str)
可以是你想要的任何东西-你的问题标题说你想检查它们是否是整数,如果是这种情况,你可以将条件更改为e.isdigit()
,如果字符串表示整数,则返回True
,否则返回False
。您正在迭代数组[“a”、“b”、“c”]
,因此使用str进行类型检查时,False
无疑是结果
一种解决方案是将n维数组展平为一维数组,然后进行检查(在示例中,我使用
您可以使用嵌套的isinstance()
和any()
:
如果您想更加严格,可以使用all()
:
如果要测试所有子列表,请再次使用all()
:
>>> another_list = [["a", "b", "c"], [1, 2, 3]]
>>> [all([isinstance(x, int) for x in y]) for y in another_list]
[False, True]
要将其转化为一个函数:
>>> all([all([isinstance(x, int) for x in y]) for y in another_list])
False
这是一个不关心内部结构的版本。我们只需检查每个元素,看看它是否为str(返回True)、iterable(检查其所有元素),否则返回False
def check(l):
return all([all([isinstance(x, int) for x in y]) for y in l])
你贴的代码怎么了?您希望得到什么输出?@deadshot我希望它返回True,但我的代码是错误的,因为它在列表中查找,而不是子列表。您必须在子列表中查找。如果您不知道其结构,请在python中搜索“扁平化”嵌套容器。这是真正的问题吗?就是这样!你是救命恩人!泰!不需要if子句all
返回true或false。如果您的问题已从整数变为字符串,请在isinstance
调用中将int
替换为str
。
>>> some_list = [["a", "b", "c"], ["d", 5, "f"]]
>>> [any([isinstance(y, int) for y in x]) for x in some_list]
[False, True]
>>> another_list = [["a", "b", "c"], [1, 2, 3]]
>>> [all([isinstance(x, int) for x in y]) for y in another_list]
[False, True]
>>> all([all([isinstance(x, int) for x in y]) for y in another_list])
False
def check(l):
return all([all([isinstance(x, int) for x in y]) for y in l])
from typing import Iterable
def check(data):
if isinstance(data, str):
return True # recursion base case
if isinstance(data, Iterable):
return all(map(check, data))
return False
if not check('a'):
raise ValueError
if check(0):
raise ValueError
lista = [["a", "b", "c"], ["d", "e", "f"]]
listb = [["a", ["b", "c", 0]], [["d", "e"], "f"]]
if not check(lista):
raise ValueError
if check(listb):
raise ValueError
print ('passed')