计算嵌套列表中的元素数量

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

我正在尝试计算嵌套列表中的元素数量,该列表如下所示:

[(1944, ['Hughes H']),
 (1940, ['Hill DK', 'Crawford GN', 'Greene HS', 'Myers J', 'Burr GO']),
 (1941,
  ['McClung CE',
   'Sumner FB',
   'Gates RR',
   'Lewis WH',
   'Haas O',
   'Haas O',
   'Gould BS',
   'Tytell AA',
   'Hatch MH']),
 (1942,
  ['Gaffron H',
   'Gardner FT',
   'Edwards PR',
   'Bruner DW',
   'Lake NC',
   'Ratner B',
   'Gaffron H',
   'Rubin J',
   'Ritter WE']),
 (1943,
  ['Bousfield G',
   'Fishbein M',
   'Faber HK',
   'Silverberg RJ',
   'Dong L',
   'Howorth MB'])]

这是用于获取此输出的代码:

d = defaultdict(list)
for k, v in authors_expanded:
        d[k].append(v)

d.items()

使用以下代码即可,只需减去一个即可:

len(d.items())-1

因为列表的第一个元素始终包含一个项目。 我正在寻找更好的解决方案。

为我提供一个好的链接也很棒,我自己似乎找不到任何链接。

python python-2.7 nested-lists
4个回答
0
投票

如果您正在查找每年的作者数量,您可以使用以下方法:

# Authors per year
authors_per_year = { year: len(authors) for year, authors in the_list }

给你这个:

{1940: 5, 1941: 9, 1942: 9, 1943: 6, 1944: 1}

或者,如果您正在寻找独特作者的数量,那么您可以使用以下方法:

# Unique authors
unique_authors = set([ a for year, authors in the_list 
                           for a in authors])

给你这套:

set(['Bousfield G',
     'Bruner DW',
     'Burr GO',
     'Crawford GN',
     'Dong L',
     'Edwards PR',
     'Faber HK',
     'Fishbein M',
     'Gaffron H',
     'Gardner FT',
     'Gates RR',
     'Gould BS',
     'Greene HS',
     'Haas O',
     'Hatch MH',
     'Hill DK',
     'Howorth MB',
     'Hughes H',
     'Lake NC',
     'Lewis WH',
     'McClung CE',
     'Myers J',
     'Ratner B',
     'Ritter WE',
     'Rubin J',
     'Silverberg RJ',
     'Sumner FB',
     'Tytell AA'])

因此

len(unique_authors)
会为您提供
28
的计数。

无论如何,我认为您的前进方向很可能是使用列表理解字典理解的某种组合。


0
投票
[ len(y) for x,y in your_list ]

输出

[1, 5, 9, 9, 6]

我采用 x,y 对,y 是嵌套列表。我正在使用

len
函数给出列表中的元素数量


0
投票

你需要的是递归。一个调用自身的函数。迭代列表时测试类型以及另一个列表是否递归地计算其中的项目。看看下面应该可以解决问题。无论嵌套列表有多少个或需要多深,这都将起作用。您还可以计算嵌套元组和字典,但如果您不需要测试它们,我会删除它们。

items = ['item1',['item2',['item3','item4']]]

def count_items(items):
    number = 0
    for i in items:
        variable_type = type(i)
        if variable_type is list or variable_type is tuple or variable_type is dict:
            number = number + count_items(i)
        else:
            number = number + 1
    return number

print count_items(items)

0
投票

我很欣赏 @0C3Danswer,但当我在 dict{dict: {[list]}} 嵌套集合上尝试时,它对我来说似乎不完整:

{1727083382: 
    {1234: ['something', 'else'],
     5678: ['yet', 'another']}}

这让我很困扰,因为@0C3D 说:

无论嵌套列表有多少个,或者需要多深,这都会起作用。

我在顶层添加了类型检查,因为键不是不恰当的,这现在对我有用。
你可能会注意到我说的是 f*** 元组

添加到

match
语句中会非常容易:

# Recursively count list/dict
def count_items(items):
    number = 0
    top_type = str(type(items)).split("'")[1]

    match top_type:
        case 'dict':
            for i in items.keys():
                variable_type = type(items[i])
        
                if variable_type is list or variable_type is tuple or variable_type is dict:
                    number = number + count_items(items[i])
                else:
                    number = number + 1
        case 'list':
            for i in items:
                variable_type = type(i)

                if variable_type is list or variable_type is tuple or variable_type is dict:
                    number = number + count_items(items)
                else:
                    number = number + 1
        case no_match:
            raise ValueError(f'{no_match} is not yet supported.')

    return number

© www.soinside.com 2019 - 2024. All rights reserved.