Accessing Elements of a Tuple

喜夏-厌秋 提交于 2020-05-23 21:30:09

问题


I am accessing an element of length 2 tuple by tuple_name[0] but the python interpreter keeps giving me error Index out of bounds.

Here is the code for reference:

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".

回答1:


Changing the final line to simply print a and running the exact code you've pasted above, I get the following output:

[]
([100], ['hello'])
([12], ['hero'])
([100, 12], ['hello', 'hero'])
([32], ['fool'])
([100, 32], ['hello', 'fool'])
([12, 32], ['hero', 'fool'])
([100, 12, 32], ['hello', 'hero', 'fool'])

So, quite clearly, the first iteration is an empty list, so does not have an element 0.




回答2:


The first thing you yield from subset is the empty list, yield [].

Naturally you can't access an element on that which is why a[0] fails.




回答3:


The first thing that subset yields is the empty list:

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

This is what's tripping up the a[0].

You probably meant to yield ([],[]) to keep the first value consistent with the rest.



来源:https://stackoverflow.com/questions/7637673/accessing-elements-of-a-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!