V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
songdg
V2EX  ›  Python

请教如何判断一个列表中有多少个列表

  •  
  •   songdg · 2019-09-04 10:23:50 +08:00 · 1946 次点击
    这是一个创建于 1667 天前的主题,其中的信息可能已经有所发展或是发生改变。
    a = ['天然气', '垃圾分类'] b = [['稀土永磁'], ['风电', '稀土永磁']],像这样的用 len 函数也判断不出来。
    10 条回复    2019-09-05 13:56:35 +08:00
    arrow8899
        1
    arrow8899  
       2019-09-04 10:42:13 +08:00   ❤️ 1
    len(list(filter(lambda x: isinstance(x, list), b)))
    gimp
        2
    gimp  
       2019-09-04 10:45:14 +08:00   ❤️ 1
    len([x for x in b if isinstance(x, list)])
    lihongjie0209
        3
    lihongjie0209  
       2019-09-04 15:09:57 +08:00
    for 循环一个一个判断啊
    xpresslink
        4
    xpresslink  
       2019-09-04 16:27:14 +08:00   ❤️ 1
    常规来说统计多维嵌套列表中的个数应该用 递归拉平列表那个程序(网上很多自己百度)中加个计数器实现。
    但是也有比较 hacker 一些的方法比如:
    >>> a = ['天然气', '垃圾分类'];b = [['稀土永磁'], ['风电', '稀土永磁']]
    >>> str(a).count('[')
    1
    >>> str(b).count('[')
    3
    >>>
    Hopetree
        5
    Hopetree  
       2019-09-04 17:03:25 +08:00
    @xpresslink 你是真的秀,哈哈哈哈

    想起以前初中做奥数题,有的数学选择题让计算三角形的角度,结果拿尺子给量出来了,而且那就是答案
    iamdaguduizhang
        6
    iamdaguduizhang  
       2019-09-05 10:40:46 +08:00
    @xpresslink Good idea !!
    songdg
        7
    songdg  
    OP
       2019-09-05 13:17:06 +08:00
    @arrow8899 谢谢帮助。
    sladesha
        8
    sladesha  
       2019-09-05 13:51:17 +08:00
    def test(l):
    ans = 0
    def getListNumber(l):
    nonlocal ans
    for item in l:
    if isinstance(item, list):
    ans += 1
    getListNumber(item)
    return ans
    return getListNumber(l)

    if __name__ == '__main__':
    List = [[1, 2, [3, [2], [1, 2]]]]
    print(test(List))
    songdg
        9
    songdg  
    OP
       2019-09-05 13:55:47 +08:00
    @gimp 谢谢,代码更短。
    songdg
        10
    songdg  
    OP
       2019-09-05 13:56:35 +08:00
    @xpresslink 神操作,谢谢。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1944 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:23 · PVG 00:23 · LAX 09:23 · JFK 12:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.