四时宝库

程序员的知识宝库

【PythonTip题库300题】第48题:子列表的数量

1、编程试题:

编写一个程序来计算列表中子列表的数量。

定义函数count_sublists(),参数为list_input。

在函数内部,返回输入列表中子列表的总数。

示例输入

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

示例输出

3


2、代码实现:

#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 , Inc. All Rights Reserved
#
# @Time      : 2024/1/11 21:44
# @Author    : fangel
# @FileName  : 48. 子列表的数量.py
# @Software  : PyCharm

def count_sublists(list_input):
    if list_input is None:
        return 0
    elif isinstance(list_input[0],list):
        return len(list_input)
    else:
        return 0

# 获取输入转为列表
list_input = eval(input())

#调用函数
print(count_sublists(list_input))


3、代码分析:

(1)注意鉴别两种异常情况,第一个是输入的列表为空,这时需要返回0;第二个是输入的列表中没有子列表,这种应该返回0;

(2)Python中的 isinstance() 函数,是Python中的?个内置函数,?来判断?个函数是否是?个已知的类型,类似 type()


4、运行结果:

输入:[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

输出:3

输入:[2, 3, 4, 5]

输出:0

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接