gpt4 book ai didi

python - 引用列表的一部分 - Python

转载 作者:太空狗 更新时间:2023-10-29 17:48:17 28 4
gpt4 key购买 nike

如果我在 python 中有一个列表,我如何创建对列表的一部分的引用?例如:

myList = ["*", "*", "*",  "*", "*", "*", "*", "*", "*"]

listPart = myList[0:7:3] #This makes a new list, which is not what I want

myList[0] = "1"

listPart[0]

"1"

这可能吗?如果可以,我该如何编码?

干杯,乔

最佳答案

你可以写一个 ListView 类型。这是我作为实验写的东西,绝不保证是完整的或没有错误的

class listview (object):
def __init__(self, data, start, end):
self.data = data
self.start, self.end = start, end
def __repr__(self):
return "<%s %s>" % (type(self).__name__, list(self))
def __len__(self):
return self.end - self.start
def __getitem__(self, idx):
if isinstance(idx, slice):
return [self[i] for i in xrange(*idx.indices(len(self)))]
if idx >= len(self):
raise IndexError
idx %= len(self)
return self.data[self.start+idx]
def __setitem__(self, idx, val):
if isinstance(idx, slice):
start, stop, stride = idx.indices(len(self))
for i, v in zip(xrange(start, stop, stride), val):
self[i] = v
return
if idx >= len(self):
raise IndexError(idx)
idx %= len(self)
self.data[self.start+idx] = val


L = range(10)

s = listview(L, 2, 5)

print L
print s
print len(s)
s[:] = range(3)
print s[:]
print L

输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<listview [2, 3, 4]>
3
[0, 1, 2]
[0, 1, 0, 1, 2, 5, 6, 7, 8, 9]

您可以在 ListView 中分配给索引,它会反射(reflect)在基础列表中。但是,在 ListView 上定义追加或类似操作没有意义。如果基础列表的长度发生变化,它也可能会中断。

关于python - 引用列表的一部分 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1788608/

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