python在检查变量是单个列表还是列表列表后应用函数

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

我打算将函数应用于变量。我事先不知道传入的变量是列表列表还是单个列表。例如

var_name = [a, b, c]
or
var_name = [[a,b,c], [d,e,f], [h,i,j]]

列表列表可以包含尽可能多的列表。如何验证变量是列表还是列表。我打算根据类型应用功能。我尝试使用len(var_name),但是列表的长度将是单个列表中的项目数,而列表的长度则是列表中的列表数。

我想要达到的目标是:

#function for list
def apply_val(lst):
    do something with single list
#function for list of list
def apply_val2(lst):
    do something with list of lists

var_name = single_list or list_of_lists
if var_name == single list
    apply_val(single_list)
else:
    apply_val(list_of_lists)

如何检查var_name是列表还是列表列表?

python
2个回答
0
投票

[list of lists并不表示什么,[["foo", "bar"], "baz"]是什么?

但是,如果您确定只能拥有“不是列表的列表”和“列表的列表”,则为:

  • 检查列表不为空
  • 然后,检查第一项的类型
if len(my_list) > 0:
  if isinstance(my_list[0], list):
    # List of list
    pass
  else:
    # Simple list
    pass

0
投票

如果单个列表始终只是值而列表列表始终仅包含列表,则可以像下面这样检查它是单个列表还是列表列表:

list1 = [1,2,3]
list2 = [[1,2,3],[1,2,3]]

if type(list2[0]) == list:
    print('list of lists')
else:
    print('single list')

如果有混合,您可以执行以下操作:

list3 = [1,[1,2,3]]

if len(set([type(element) for element in list3])) > 1:
    print('mixed')
© www.soinside.com 2019 - 2024. All rights reserved.