gpt4 book ai didi

python - 列表/数组范围外的零

转载 作者:行者123 更新时间:2023-11-28 19:56:22 26 4
gpt4 key购买 nike

使用 Python 列表

L=[1,2,3,4]

如果 m0,1,2,3 不同,我希望 L[m] = 0,即:

...
L[-2]=0
L[-1]=0
L[0]=1
L[1]=2
L[2]=3
L[3]=4
L[4]=0
L[5]=0

L[-2:2] = [0, 0, 1, 2]

这不适用于经典列表或数组。执行此操作的好方法是什么?

编辑:这是一个很好的解决方案(这里给出了一个答案):

class MyList(list):
def __getitem__(self, index):
return super(MyList, self).__getitem__(index) if index >= 0 and index < len(self) else 0

但我还是无法拥有

L[-2:2] = [0, 0, 1, 2]

最佳答案

您可以将 L 转换为字典:

In [1]: L=[1,2,3,4]

In [2]: D=dict([(x, y) for x, y in enumerate(L)])

In [3]: [D.get(i, 0) for i in xrange(-3, 5)]
Out[3]: [0, 0, 0, 1, 2, 3, 4, 0]

关于python - 列表/数组范围外的零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20217843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com