[英]List Enumeration in Python
The snippet below is from a code tracing exercise. 下面的代码片段来自代码跟踪练习。
import copy
def ct1(A, B, C, D, E):
result = [ ]
# 0 1 2 3 4 5 6 7 8 9
pairs = [(A,B),(A,C),(A,D),(A,E),(B,C),(B,D),(B,E),(C,D),(C,E),(D,E)]
for i,pair in enumerate(pairs):
(L, M) = pair
if (L is M): result.append(i)
elif (L == M): result.append(10*i)
return result
def f(L):
L[0] += 1
return L
A = list(range(3))
B = copy.copy(A)
C, D, E = A, B+[ ], f(B)
print(ct1(A, B, C, D, E))
The part I'm confused about is the enumeration used in the for loop. 我很困惑的部分是for循环中使用的枚举。 From the documentation for enumerate() it looks like
pair
should had have values like: 从enumerate()的文档来看,
pair
应该具有类似以下的值:
(0, ([0, 1, 2], [1, 1, 2]))
(1, ([0, 1, 2], [0, 1, 2]))
(2, ([0, 1, 2], [0, 1, 2]))
(3, ([0, 1, 2], [1, 1, 2]))
(4, ([1, 1, 2], [0, 1, 2]))
(5, ([1, 1, 2], [0, 1, 2]))
(6, ([1, 1, 2], [1, 1, 2]))
(7, ([0, 1, 2], [0, 1, 2]))
during the iteration, which means 'L'
should have values from 0
through 7
and 'M'
, the tuples ([0, 1, 2], [1, 1, 2])
through ([0, 1, 2], [0, 1, 2])
. 在迭代过程中,这意味着
'L'
值应介于0
到7
而'M'
值应介于元组([0, 1, 2], [1, 1, 2])
到([0, 1, 2], [0, 1, 2])
。 However when I run this code through the debugger, I see both L
and M
are lists instead. 但是,当我通过调试器运行此代码时,我看到
L
和M
都是列表。 For example, when i = 0, L = [0, 1, 2] and M = [1, 1, 2]
and so forth. 例如,当
i = 0, L = [0, 1, 2] and M = [1, 1, 2]
,依此类推。 Can someone please explain what is going on? 有人可以解释发生了什么吗?
With the line for i,pair in enumerate(pairs):
, i
gets the index values in the list pairs
and goes from 0 to 9 while pair
gets the values from the list pairs
one by one. 用
for i,pair in enumerate(pairs):
的那一行在for i,pair in enumerate(pairs):
, i
获取列表pairs
的索引值,并从0到9,而pair
从列表pairs
获取值。 So for i = 0
, the pair
is ([0, 1, 2], [1, 1, 2])
. 因此,对于
i = 0
,该pair
为([0, 1, 2], [1, 1, 2])
。 Then you call (L, M) = pair
and this means L
get the first list while M
gets the second list in the tuple. 然后调用
(L, M) = pair
,这意味着L
获得元组中的第一个列表,而M
获得第二个列表。 Hope this helps. 希望这可以帮助。
Of course L
and M
are lists. 当然,
L
和M
是列表。 If you run 如果你跑
pairs = [(A,B),(A,C),(A,D),(A,E),(B,C),(B,D),(B,E),(C,D),(C,E),(D,E)]
for i, pair in enumerate(pairs):
print(i, pair)
you will get the desired result. 您将获得理想的结果。 So the tuple you are looking for is saved in
pairs
. 所以,你正在寻找的元组保存在
pairs
。 With the line 用线
# ...
(L, M) = pair
# ...
you split up the tuple referenced by pair
into its elements, which are – in the first iteration – the two lists referenced by A
and B
. 你分裂通过引用的元组
pair
进入它的元素,它们是-在第一次迭代-通过引用的两个列表A
和B
。
The above line essentially means 上面的线本质上意味着
(L, M) = (A, B)
which is equivalent to 相当于
L, M = A, B
which in turn means "assign A
to L
and assign B to M
". 依次表示“将
A
分配给L
,将B分配给M
”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.