Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

python - Get a pointer to a list element

I was wondering if it was possible to get a "pointer" to an element in a python list. That way, I would be able to access my element directly without needing to know my element's index. What I mean by that is that in a list, you can add elements anywhere; at the start, in the middle or even at the end, yet the individual elements aren't moved from their actual memory location. In theory, it should be possible to do something like:

myList = [1]

[1]

element = &myList[0]

element would act as a pointer here.

myList.insert(0, 0)
myList.append(2)

[0, 1, 2]

At this point, I would still be able to access the element directly even though it's index within the list has changed.

The reason I want to do this is because in my program, it would be way too tedious to keep track of every item I add to my list. Each item is generated by an object. Once in a while, the object has to update the value, yet it can't be guaranteed that it will find its item at the same index as when it was added. Having a pointer would solve the problem. I hope that makes sense.

What would be the right way to do something like that in Python?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's no concept of pointers on python (at least that I'm aware of).

In case you are saving objects inside your list, you can simply keep a reference to that object.

In the case you are saving primitive values into your list, the approach I would take is to make a wrapper object around the value/values and keep a reference of that object to use it later without having to access the list. This way your wrapper is working as a mutable object and can be modified no matter from where you are accesing it.

An example:

class FooWrapper(object):
    def __init__(self, value):
         self.value = value

# save an object into a list
l = []
obj = FooWrapper(5)
l.append(obj)

# add another object, so the initial object is shifted
l.insert(0, FooWrapper(1))

# change the value of the initial object
obj.value = 3
print l[1].value # prints 3 since it's still the same reference

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...