python - 访问元组的元素

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

最佳答案

将最后一行更改为简单地 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。

关于python - 访问元组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7637673/

相关文章:

python - 在seaborn barplot之前隐藏文本

python - 如何根据我自己的训练数据微调来自 OpenAI 的 Whisper ASR 的模型?

python - Apache Zeppelin 上没有使用 python 解释器的 runParagraph()

list - 删除具有相同元素但顺序不同的元组列表的函数

C++:调用 tuple_transpose 函数时没有匹配的函数调用

python - Tensorflow:为什么 tf.get_default_graph() 不是当前图?

python - 无法使用 Keras fit_generator 重现结果

c# - 在 C# 中创建元组时编译错误,三元运算符周围没有括号

python - 根据元组中的索引删除重复的元组值

Python:为什么这个元组打印结果和 "None"?另外:有没有更好的方法来实现结果?