【问题标题】:How to Sum up number of list如何总结列表的数量
【发布时间】:2016-05-19 12:05:26
【问题描述】:

我想总结一个嵌套列表中的列表总数。

datalist = [['a', 'b', 'c', 'a'], [['b', 'd', 'a', 'c'], ['a', 'a', 'a', 'b']], ['a', 'b', 'g', 'h'], [['x', 'z', 'c', 'c'], ['b', 'c', 'b', 'a']]]

列表总和为 6

方法 1

给我 4 个

print sum(1 for x in datalist if isinstance(x, list))
# 4

方法 2

给我 8 个

def count_list(l):
    count = 0
    for e in l:
        if isinstance(e, list):
            count = count + 1 + count_list(e)
    return count

print count_list(datalist)
#8

如何总结列表的数量?

【问题讨论】:

  • 因为您确实有四个列表。不过,其中两个列表本身包含列表。
  • 两个lists 在一个list 中仍然算作1。您可以编写一个递归方法来计算内部列表。
  • 有嵌套列表。也可以有多层嵌套吗?
  • 也许使用pprint.pprint(datalist) 来查看嵌套层。
  • 这不应被标记为重复。市场重复的帖子没有为 OP 的问题提供所需的解决方案。

标签: python list sum


【解决方案1】:

这是工作流程:

>>> def count(local_list):
...     sum1 = 0
...     for l in local_list:
...             if not isinstance(l,list):
...                     return 1 
...             else:
...                     sum1+= count(l) 
...     
...     return sum1
... 
>>> count([['a', 'b', 'c', 'a'], [['b', 'd', 'a', 'c'], ['a', 'a', 'a', 'b']], ['a', 'b', 'g', 'h'], [['x', 'z', 'c', 'c'], ['b', 'c', 'b', 'a']]])
6

【讨论】:

  • @MysticCode 如果回答了您的问题,您可以接受答案。
  • 不使用递归函数是否可以解决?
  • 可能会有……得考虑一下。
【解决方案2】:

您可以通过一些递归来做到这一点,正如您已经在您的一个函数中展示的那样

如果项目是 list 并且项目不包含任何列表,则该函数只会将 1 添加到 count。否则,该函数会再次递归调用该项目。

datalist = [['a', 'b', 'c', 'a'], [['b', 'd', 'a', 'c'], ['a', 'a', 'a', 'b']], ['a', 'b', 'g', 'h'], [['x', 'z', 'c', 'c'], ['b', 'c', 'b', 'a']]]

def count_nested_lists(lst):
    count = 0
    for item in lst:
        if isinstance(item, list):
            if not any(isinstance(l, list) for l in item):
                count += 1
            else:
                count += count_nested_lists(item)
    return count

print(count_nested_lists(datalist))
# 6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    相关资源
    最近更新 更多