Reference to Part of List - Python

后端 未结 4 1157
暖寄归人
暖寄归人 2020-12-11 02:01

If I have a list in python, how can I create a reference to part of the list? For example:

myList = [\"*\", \"*\", \"*\",  \"*\", \"*\", \"*\", \"*\", \"*\",         


        
4条回答
  •  轮回少年
    2020-12-11 02:33

    I think that it is impossible. It would lead to many possible errors, for example: what when you append the list which is reference to part of a bigger list? Shall next element in big list be replaced, or inserted?

    As far as I know, silce is internal mechanism for getting elements of the list. They do not create new list object, referencing to parts of older list object. Islice just iterates over the elements given by slice, it is also not the reference, but the actual object - changing it doesn't affect original list. Or am I mistaken?

    As in comment, and that solution contributes really to Mr. Bastien, you can do:

    sliceobject = slice(0,7,3)
    for i in xrange(sliceobject.start, sliceobject.stop, sliceobject.step)
        myList[i] = whatever
    

    That way you can access each specified element of your list by reference.

提交回复
热议问题