python:计算父列表中的项目数

时间:2017-03-10 17:46:42

标签: python list iteration

假设我有以下列表:

yrs = [2016, 2017]
months = [['June'], ['January', 'February']]
names = [[['John', 'Mike']], [['Sara'], ['Steph', 'James']]]

我想计算与每年相关的名字数量。因此,对于上面的示例,我将获得2016年的2个名称和2017年的3个名称。所以我想我需要一种方法来在每年迭代时展平列表。

for yr_index in range(len(names)):
    print yrs[yr_index], '-->', names[yr_index]

# 2016 --> [['John', 'Mike']]
# 2017 --> [['Sara'], ['Steph', 'James']]

4 个答案:

答案 0 :(得分:1)

我认为您想要使用zip功能,例如

>>> list(zip(yrs, months, names))
[(2016, ['June'], [['John', 'Mike']]), (2017, ['January', 'February'], [['Sara'], ['Steph', 'James']])]

现在你可以坚持这个循环并再次拉链:

>>> for yr, yr_months, yr_names in zip(yrs, months, names):
...     for month, month_names in zip(yr_months, yr_names):
...         print(yr, month, month_names)
... 
2016 June ['John', 'Mike']
2017 January ['Sara']
2017 February ['Steph', 'James']

或者(但在我看来并不清楚),使用enumerate(我将内循环作为练习):

>>> for yr_index, yr in enumerate(yrs):
...     print(yr, months[yr_index])
... 
2016 ['June']
2017 ['January', 'February']

您可能知道len(my_list)给出了列表中的项目数。您可以使用上面的循环计数器来计算每年的名称数量。或者,将外部循环与生成器理解和sum函数组合以获取列表列表中的项目数:

>>> x = [[1,2], [3, 4]]
>>> sum(len(sub_list) for sub_list in x)
4

答案 1 :(得分:0)

假设您想要它在数据结构中而不仅仅是打印:

outcome = {}

for year_index, year in enumerate(yrs):
    outcome[str(year)] = names[year_index]

print(outcome)

# {'2017': [['Sara'], ['Steph', 'James']], '2016': [['John', 'Mike']]}

否则:

for year_index, year in enumerate(yrs):
    print('{0} --> {1}'.format(str(year), names[year_index]))

# 2016 --> [['John', 'Mike']]
# 2017 --> [['Sara'], ['Steph', 'James']]

答案 2 :(得分:0)

您可以获取每年的名称数量,或与每年相关的名单的平面列表,如下所示:

yrs = [2016, 2017]
months = [['June'], ['January', 'February']]
names = [[['John', 'Mike']], [['Sara'], ['Steph', 'James']]]

for yr_index in range(len(names)):
    # print the number of names for each year
    print yrs[yr_index], '-->', len([item for sublist in names[yr_index] for item in sublist])

    # print the names for each year
    print yrs[yr_index], '-->', [item for sublist in names[yr_index] for item in sublist]

打印:

2016 --> 2
2016 --> ['John', 'Mike']
2017 --> 3
2017 --> ['Sara', 'Steph', 'James']

答案 3 :(得分:0)

如果您正在寻找每年的数字,这将有效:

result = {}
for index, year in enumerate(yrs):
    result[year] = sum([len(sublist) for sublist in names[index]])

>>> result
{2016: 2, 2017: 3}

简短而简单。