Python 使用while循环和for循环处理元组

Python 使用while循环和for循环处理元组,python,Python,我必须编写一个函数,使用Python返回元组的每个可选元素。例如:如果输入是(1,“hi”,2,“hello”,5);我的输出应该是(1,2,5)。我使用while循环和[::2]得到了答案。但当我尝试循环时,我会遇到这样的错误:元组占用1个位置参数,而输入有5个位置参数。那么,有人能给我一个等价的for循环函数来表示我所附加的while循环函数吗? “” def oddTuples(aTup): ''' 一个元组 返回:tuple,aTup的每个其他元素。 ''' #你的代码在这里 rTup=

我必须编写一个函数,使用Python返回元组的每个可选元素。例如:如果输入是
(1,“hi”,2,“hello”,5)
;我的输出应该是
(1,2,5)
。我使用while循环和[::2]得到了答案。但当我尝试循环时,我会遇到这样的错误:元组占用1个位置参数,而输入有5个位置参数。那么,有人能给我一个等价的for循环函数来表示我所附加的while循环函数吗? “”

def oddTuples(aTup):
'''
一个元组
返回:tuple,aTup的每个其他元素。
'''
#你的代码在这里
rTup=()
索引=0
当指数
尝试以下代码:

def oddTuples(aTup):
    out=()
    for i in range(len(aTup)):
        if i%2==0:
            out = out + (aTup[i],)
return out
aTup=(1,"hi",2,"hello",5)
print oddTuples(aTup)
运行上述代码时的输出:

(1, 2, 5)

您还可以使用
range
提供适当的索引来访问元组值<代码>范围
可以采用1、2或3个参数

如果将一个参数输入到
范围
,例如
范围(5)
,它将生成一个从0开始并在5处停止的整数序列。(5将被排除在外,因此仅给出0、1、2、3、4。)

如果输入两个参数,例如
范围(3,5)
,则3是开始索引,5是停止索引。注5不包括在内

如果取三个数字,如
范围(0,10,2)
,第一个参数是要开始的索引;第二个是结束索引,第三个是步长。我们在下面演示两种方法

def oddTuples(aTup):
    rTup = ()
    for i in range(len(aTup)):  # will loop over 0, 1, ..., len(aTup)-1
        if i % 2 == 0:          # a condition to filter out values not needed
            rTup += (aTup[i],)
    return rTup

def oddTuples(aTup):
    rTup = ()
    for i in range(0, len(aTup), 2):  # the 2 is to specify the step size
        rTup += (aTup[i],)            # 0, 2, 4, ... till the sequence is exausted.
    return rTup

[n的项,枚举(我的元组)中的项,如果不是n%2]
使用条件列表理解枚举。感谢@Alexander,但我对Python非常陌生,目前正在Python上学习MITx课程。所以,我对枚举函数不是很熟悉。你能解释一下吗?这个枚举函数是什么?对我来说有点新,因为我刚刚进入python,正在学习MITx 6.00.1x课程。enumerate(var)将返回一个元组(i,x),其中i是索引,x是var的第i个元素。var可以是列表或元组或任何其他Iterables,我也做了同样的事情,先生。但我不知道为什么会有问题。当我复制粘贴您的代码时,它工作得很好。谢谢你的帮助。很高兴知道这有帮助:)
(1, 2, 5)
def oddTuples(aTup):
    rTup = ()
    for i in range(len(aTup)):  # will loop over 0, 1, ..., len(aTup)-1
        if i % 2 == 0:          # a condition to filter out values not needed
            rTup += (aTup[i],)
    return rTup

def oddTuples(aTup):
    rTup = ()
    for i in range(0, len(aTup), 2):  # the 2 is to specify the step size
        rTup += (aTup[i],)            # 0, 2, 4, ... till the sequence is exausted.
    return rTup