Python:将元组的元素添加到空元组

Python: Adding elements of a tuple to an empty tuple

def oddTuples(aTup):
    '''
    aTup: a tuple

    returns: tuple, every other element of aTup. 
    '''
    num = len(aTup)
    newtup = ()
    for i in range(0,num+1):
        if (i % 2 == 1):
            newtup += aTup[i]
        else:
            continue
    return newtup

该函数将一个元组作为输入,returns 一个包含 aTup 的奇数项的元组,即 aTup[1]aTup[3] 等。在第十行,
newtup += aTup[i]
我收到一个错误。请详细说明原因,并请更正问题。我知道这个问题也有一个单一的解决方案,但我不想要那个。我想知道我在第十行的错误的原因和更正。我很乐意得到帮助。

你的范围函数中的 (num + 1)extra,你只需要 num。(我想你得到了索引错误。)

for i in range(0,num):
    if (i % 2 == 1):
        newtup += aTup[i]
    else:
        continue

是的,我监督了元组错误,@zondo

您正在将数字本身添加到元组中。只能将元组添加到元组中。将 newtup += aTup[i] 更改为 newtup += (aTup[i],)。这将修复当前错误,但正如@Rockybilly 指出的那样,使用 range(0, num+1) 是错误的。那将使用一个太多的数字。将其更改为 range(0, num)。您也可以省略 0,因为这是 range().

的默认值

元组是不可变的,因此您不能附加到它们。我想将值附加到列表中,完成后将列表更改为元组。

def oddTuples(aTup):
    newlist = []
    for index, element in enumerate(aTup):
        if index % 2 == 1:
            newlist.append(element)
    return tuple(newlist)
aTup[1::2]

如果 aTup 至少有 2 个元素,应该可以工作。

切片是 Python 最好的东西之一。