访问元组元素
我在用 tuple_name[0]
来访问一个长度为2的元组的元素,但Python解释器总是给我报错 Index out of bounds
。
这里有一段代码供参考:
def full(mask):
v = True
for i in mask:
if i == 0:
v = False
return v
def increment(mask, l):
i = 0
while (i < l) and (mask[i] == 1):
mask[i] = 0
i = i+1
if i < l:
mask[i] = 1
def subset(X,Y):
s = len(X)
mask = [0 for i in range(s)]
yield []
while not full(mask):
increment(mask, s)
i = 0
yield ([X[i] for i in range(s) if mask[i]] , [Y[i] for i in range(s) if mask[i]])
x = [100,12,32]
y = ['hello','hero','fool']
s = subset(x,y) # s is generator
for a in s:
print a[0] # Python gives me error here saying that index out of
# bounds, but it runs fine if I write "print a".
3 个回答
1
首先,subset
返回的是一个空列表:
def subset(X,Y):
...
yield []
...
这就是让 a[0]
出现问题的原因。
你可能是想用 yield ([],[])
这样来保持第一个值和后面的值一致。
3
你从 subset
这个函数里得到的第一个结果是一个空列表,也就是 yield []
。
因为这个列表是空的,所以你不能访问里面的任何元素,这就是为什么 a[0]
会出错的原因。
5
把最后一行改成简单的 print a
,然后运行你上面粘贴的代码,我得到了以下输出:
[]
([100], ['hello'])
([12], ['hero'])
([100, 12], ['hello', 'hero'])
([32], ['fool'])
([100, 32], ['hello', 'fool'])
([12, 32], ['hero', 'fool'])
([100, 12, 32], ['hello', 'hero', 'fool'])
所以,很明显,第一次循环的时候是一个空列表,也就是说没有第0个元素。