推荐学习书目
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 · Sep 4, 2019 · 2791 views
    This topic created in 2467 days ago, the information mentioned may be changed or developed.
    a = ['天然气', '垃圾分类'] b = [['稀土永磁'], ['风电', '稀土永磁']],像这样的用 len 函数也判断不出来。
    10 replies    2019-09-05 13:56:35 +08:00
    arrow8899
        1
    arrow8899  
       Sep 4, 2019   ❤️ 1
    len(list(filter(lambda x: isinstance(x, list), b)))
    gimp
        2
    gimp  
       Sep 4, 2019   ❤️ 1
    len([x for x in b if isinstance(x, list)])
    lihongjie0209
        3
    lihongjie0209  
       Sep 4, 2019
    for 循环一个一个判断啊
    xpresslink
        4
    xpresslink  
       Sep 4, 2019   ❤️ 1
    常规来说统计多维嵌套列表中的个数应该用 递归拉平列表那个程序(网上很多自己百度)中加个计数器实现。
    但是也有比较 hacker 一些的方法比如:
    >>> a = ['天然气', '垃圾分类'];b = [['稀土永磁'], ['风电', '稀土永磁']]
    >>> str(a).count('[')
    1
    >>> str(b).count('[')
    3
    >>>
    Hopetree
        5
    Hopetree  
       Sep 4, 2019
    @xpresslink 你是真的秀,哈哈哈哈

    想起以前初中做奥数题,有的数学选择题让计算三角形的角度,结果拿尺子给量出来了,而且那就是答案
    iamdaguduizhang
        6
    iamdaguduizhang  
       Sep 5, 2019
    @xpresslink Good idea !!
    songdg
        7
    songdg  
    OP
       Sep 5, 2019
    @arrow8899 谢谢帮助。
    sladesha
        8
    sladesha  
       Sep 5, 2019
    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
       Sep 5, 2019
    @gimp 谢谢,代码更短。
    songdg
        10
    songdg  
    OP
       Sep 5, 2019
    @xpresslink 神操作,谢谢。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   899 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 22:37 · PVG 06:37 · LAX 15:37 · JFK 18:37
    ♥ Do have faith in what you're doing.