将列表添加到循环字典中仅添加最后一个列表

时间:2019-10-13 00:56:27

标签: python python-3.x

完成向current_page列表中添加项目后,应将列表添加到page_dic词典中,然后将其删除。它可以正确建立列表,但似乎只会添加最后一个。

代码:

# Example Item List
items = ['a', 'b', 'c', 'd', 'e' ]


# Build Page Dictionary
page_dic = {}
page_amount = 2

page_count = 1
current_page = []

print(f'All Items: {items}')
for item in items:
    if len(current_page) == page_amount:
        print(f'To Add: {current_page}')
        page_dic[f'page_{page_count}'] = current_page
        page_count += 1

        del current_page[:]

        current_page.append(item)
    else:
        current_page.append(item )

print(f'To Add: {current_page}')
page_dic[f'page_{page_count}'] = current_page

print(f'Result: {page_dic}')

预期结果: {'page_1': ['a', 'b'], 'page_2': ['c', 'd'], 'page_3': ['e']}

结果: {'page_1': ['e'], 'page_2': ['e'], 'page_3': ['e']}

0 个答案:

没有答案