如何将列表强制为固定大小? [英] How to force a list to a fixed size?

查看:70
本文介绍了如何将列表强制为固定大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 3 中,我想创建一个列表,其中包含输入的最后 5 个变量.

In Python 3, I want to create a list that will contain the last 5 variables entered into it.

这是一个例子:

>>>l = []
>>>l.append('apple')
>>>l.append('orange')
>>>l.append('grape')
>>>l.append('banana')
>>>l.append('mango')
>>>print(l)
['apple','orange','grape','banana','mango']
>>>l.append('kiwi')
>>>print(l)
['orange','grape','banana','mango','kiwi'] #only 5 items in list

那么,在python中,有没有办法实现上面演示的内容?变量不需要是列表,我只是举个例子.

So, in python, is there any way to achieve what is demonstrated above? The variable does not need to be a list, I just used it as an example.

推荐答案

您可能想要使用 collections.deque 对象改为使用 maxlen 构造函数参数:

You might want to use a collections.deque object with the maxlen constructor argument instead:

>>>l = collections.deque(maxlen=5)
>>>l.append('apple')
>>>l.append('orange')
>>>l.append('grape')
>>>l.append('banana')
>>>l.append('mango')
>>>print(l)
deque(['apple','orange','grape','banana','mango'], maxlen=5)
>>>l.append('kiwi')
>>>print(l)
deque(['orange','grape','banana','mango','kiwi'], maxlen=5) #only 5 items in list

这篇关于如何将列表强制为固定大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆