限制列表python的长度

时间:2013-02-26 07:02:19

标签: python

我不知道这个问题是否在某个地方被问过,但我没找到。

我将元素附加到列表中。

thr_core0 +=[fpid[thread]]

这种情况会定期发生.. 在时间0:

thr_core0 [9886,9890]

在时间1:

thr_core0 [9886,9890,9886,9890]

是否可以将列表的长度限制为2.

我知道可以使用deque。但也可以使用lists

使用deque,我们这样做:

thr_core0 += [deque([0]*2,maxlen=2)]

这些是我在Google上搜索过的关键字:limit list length python

1 个答案:

答案 0 :(得分:2)

它不漂亮,但你可以把它分开:

thr_core0 = (thr_core0 + [fpid[thread]])[:2]

这将始终确保the_core0最多包含两个元素。