I'm trying to create a reference to a value in a list and then modify that value in a loop. However, I can't seem to figure out how to sort the data without grabbing its contents.value
with list comprehension. What I have so far is:
from ctypes import c_long, pointer
class A:
def __init__(self):
self.arg1 = c_long(1)
self.arg2 = c_long(2)
self.arg3 = c_long(3)
objB = [A() for _ in range(5)]
objC = [pointer(_objB.arg3) for _objB in objB]
for i in range(5):
objC[0].contents.value = i
objC = sorted(objC)
which fails. I found a workaround where the loop becomes:
for i in range(5):
objC[0].contents.value = i
objC = sorted([_objC.contents.value for _objC in objC])
But this slows the program down and loses the pointer reference to objB
. How can I correctly sort the data in objC
reference list?
Use the key
option to use the value when sorting.
objC = sorted(objC, key=lambda x: x.contents.value)
You may also want to use objC.sort()
to sort the list in place, rather than creating a new list.