2014-11-01 18 views
1

我試着去計算一個嵌套列表元素的數量,名單如下:計數數量

[(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 

由於列表的第一個元素始終包含一個項目。 我正在尋找更好的解決方案。

給我提供一個很好的鏈接也很棒,我似乎找不到任何我自己。

+1

你想成爲這個例子的結果是什麼? – 2014-11-01 21:57:35

+0

計數什麼?字典中的條目數量?這將是'len(d)',不需要調用'd.items()'。你能以什麼方式解釋'len(d.items()) - 1'給你你需要的答案嗎? – Soravux 2014-11-01 23:54:10

回答

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計數。

無論如何,我認爲你的前進方向很可能是使用list comprehensionsdict comprehension的某種組合。

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
[ len(y) for x,y in your_list ] 

輸出

[1, 5, 9, 9, 6] 

我正在x,y對,y是嵌套列表。我使用len功能給列表中