在Python中访问元组的元素

时间:2011-10-03 16:15:44

标签: python tuples

我正在通过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"

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 个答案:

答案 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'])

所以,很明显,第一次迭代是一个空列表,的元素也是如此。

答案 1 :(得分:3)

您从subset获得的第一件事是空列表yield []

当然,您无法访问a[0]失败的元素。

答案 2 :(得分:1)

subset产生的第一件事是空列表:

def subset(X,Y):
    ...
    yield []
    ...

这是绊倒a[0]

您可能希望yield ([],[])保持第一个值与其余值保持一致。