Python从循环中返回所有项目?

时间:2016-08-05 12:33:48

标签: python-3.x

我无法想象如何使用此代码返回所有项目:

@staticmethod
    def create_dataset():
        cols = Colleagues.get_all_colleagues()
        cols_abs = ((col['Firstname'] + " " + col['Surname'], col['Absences']) for col in cols)
        for col in cols_abs:
            dataset = list()
            sum_days = list()
            for d in col[1]:
                start_date = d[0]
                end_date = d[1]
                s = datetime.strptime(start_date, "%Y-%m-%d")
                e = datetime.strptime(end_date, "%Y-%m-%d")
                startdate = s.strftime("%b-%y")
                days = numpy.busday_count(s, e) + 1
                sum_days.append(days)
                days_per_month = startdate, days
                dataset.append(days_per_month)
            dict_gen1 = dict(dataset)
            comb_days = sum(sum_days)
            dict_gen2 = {'Name': col[0], 'Spells': len(col[1]), 'Total(Days)': comb_days}
            dict_comb = [{**dict_gen1, **dict_gen2}]
            return dict_comb

它只返回第一个" col"。如果我将return语句移到循环之外,它只返回我的数据集中的最后一项。这是从col_abs返回的输出:

('Jonny Briggs', [['2015-08-01', '2015-08-05'], ['2015-11-02', '2015-11-06'], ['2016-01-06', '2016-01-08'], ['2016-03-07', '2016-03-11']])
('Matt Monroe[['2015-12-08', '2015-12-11'], ['2016-05-23', '2016-05-26']])
('Marcia Jones', [['2016-02-02', '2016-02-04']])
('Pat Collins', [])
('Sofia Marowzich', [['2015-10-21', '2015-10-30'], ['2016-03-09', '2016-03-24']])
('Mickey Quinn', [['2016-06-06', '2016-06-08'], ['2016-01-18', '2016-01-21'], ['2016-07-21', '2016-07-22']])
('Jenifer Andersson', [])
('Jon Fletcher', [])
('James Gray', [['2016-04-01', '2016-04-06'], ['2016-07-04', '2016-07-07']])
('Matt Chambers', [['2016-05-02', '2016-05-04']])

任何人都可以帮助我更好地理解这一点,因为我想要返回一个" dict_comb"对于col_abs中的每个条目?

1 个答案:

答案 0 :(得分:1)

return语句替换为yield语句。这将允许您的方法继续循环,同时"屈服"或在每次迭代后返回值。