在单独列表中有多个参考; Python [英] Multiple references in separate lists; Python

查看:68
本文介绍了在单独列表中有多个参考; Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基本上创建引用以绘制多个关系并将它们存储在列表或字典中.

I'm trying to basically create references to plot multiple relationships and store them in a list or possibly a dictionary.

基本上:

variable1 = 10

//在这种情况下,"ref"表示该变量应为引用)
listA = [variable1(ref), variable2, variable3]
listB = [variable1(ref), variable4, variable5]

//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 listA:
i = i + 10

for i in listB:
i = i + 10

for i in listB:
i = i + 10

print listA[0]
//应该打印30

print listA[0]
//Should print 30

print listB[0]
//应该打印30

print listB[0]
//Should print 30

如何将对同一变量的两个引用拆分为两个单独的列表?

How can I split two references to the same variable into two separate lists?

推荐答案

两个包含相同集合键的列表,例如字典,该怎么办?

What about two lists, each containing keys of the same collection, say dictionary?

例如:

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]]

示例示例

或使用包装器类:

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])

想法示例

最后,或使用嵌入式列表:

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]

示例示例

请注意,第一个示例将ListX成员的 all 全部视为引用",而后两个示例将成员视为值",除非您将其设为SharedInt() s或将其括在其中分别列出.

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.

换句话说,


LISTA[1] = 21 # First example
ListA[1] = 11 # Second, third examples

这篇关于在单独列表中有多个参考; Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆