问题
I'm trying to basically create references to plot multiple relationships and store them in a list or possibly a dictionary.
Basically:
variable1 = 10
//in this case, 'ref' denotes that the variable should be a reference)listA = [variable1(ref), variable2, variable3]
listB = [variable1(ref), variable4, variable5]
for i in listA:
i = i + 10
for i in listB:
i = i + 10
print listA[0]
//Should print 30
print listB[0]
//Should print 30
How can I split two references to the same variable into two separate lists?
回答1:
What about two lists, each containing keys of the same collection, say dictionary?
For example:
MASTER = [10,11,12,13,14]
LISTA = [0,1,2]
LISTB = [0,3,4]
for i in LISTA: MASTER[i] += 10
for i in LISTB: MASTER[i] += 10
print MASTER[LISTA[0]]
print MASTER[LISTB[0]]
ideone example
Or using a wrapper class:
class SharedInt:
val = None
def __init__(self, v): self.val = v
def __add__(self, a):
self.val += a
return self.val
def __int__(self): return self.val
v1 = SharedInt(10)
listA = [v1, 11, 12]
listB = [v1, 13, 14]
for i in listA: i += 10
for i in listB: i += 10
print int(listA[0])
print int(listB[0])
ideone example
Lastly, or using embedded lists:
v1 = [10]
listA = [v1, 11, 12]
listB = [v1, 13, 14]
for i in listA:
if isinstance(i, list): i[0] += 10
else: i += 10
for i in listB:
if isinstance(i, list): i[0] += 10
else: i += 10
print listA[0]
print listB[0]
ideone example
Note that the first example treats all of your ListX members as "references" while the last two examples treats the members as "values", unless you make them SharedInt()s or enclose them in a list respectively.
In other words,
LISTA[1] = 21 # First example ListA[1] = 11 # Second, third examples
来源:https://stackoverflow.com/questions/18937708/multiple-references-in-separate-lists-python