我有一个列表l = [1, 2, 3]
,我想要l[2->infinity] == 3
。基本上看起来像[1, 2, 3, 3, 3, 3, ...]
。我尝试过:
[1, 2, *3]
或
[1, 2, 3, ...]
反正有为索引范围添加“默认元素”吗?
说明
我不想重复元素n
次,因为我不能在列表的长度之外进行索引。我实际上想为2->infinity
中的所有索引提供一个值。该索引范围的某种默认值。
答案 0 :(得分:8)
我能想到的最好的方法是将两个迭代器链接在一起,就像这样:
from itertools import *
chain([1, 2], repeat(3))
REPL示例:
>>> list(islice(chain([1, 2], repeat(3)), 10))
[1, 2, 3, 3, 3, 3, 3, 3, 3, 3]
答案 1 :(得分:1)
或者,克里斯回答,您可以创建自己的生成器:
def inf3():
yield 1
yield 2
while True:
yield 3
>>> g = inf3()
>>> [next(g) for _ in range(100)]
[1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]