Skip to main content
 首页 » 编程设计

python之来自 edX MIT 类(class)的介绍性 Python 任务

2025年05月04日13mq0036

我最近开始在 edX 上的 MIT 类(class)中学习 Python。

但是,我在某些练习中遇到了一些麻烦。这是其中之一:

“编写一个名为 oddTuples 的过程,它以一个元组作为输入,并返回一个新的元组作为输出,其中复制输入元组的所有其他元素,从第一个开始。所以如果测试是元组 (' I', 'am', 'a', 'test', 'tuple'), 然后在这个输入上评估 oddTuples 将返回元组 ('I', 'a', 'tuple')。"

根据讲座,正确的代码如下:

def oddTuples(aTup): 
   ''' 
   aTup: a tuple 
 
   returns: tuple, every other element of aTup. 
   ''' 
    # a placeholder to gather our response 
    rTup = () 
    index = 0 
 
    # Idea: Iterate over the elements in aTup, counting by 2 
    #  (every other element) and adding that element to 
    #  the result 
    while index < len(aTup): 
        rTup += (aTup[index],) 
        index += 2 
 
    return rTup 

但是,我尝试用下面的代码以不同的方式自己解决它:

def oddTuples(aTup): 
    ''' 
   aTup: a tuple 
 
   returns: tuple, every other element of aTup. 
   ''' 
    # Your Code Here 
    bTup=() 
    i=0 
    for i in (0,len(aTup)-1): 
        if i%2==0: 
            bTup=bTup+(aTup[i],) 
            print(bTup) 
        print(i) 
        i+=1 
    return bTup 

但是,我的解决方案不起作用,而且我无法理解原因(我认为它应该与导师提供的代码做的事情基本相同)。

请您参考如下方法:

我只想补充一点,这个问题的 pythonic 解决方案使用了具有步长的切片,并且是:

newTuple = oldTuple[::2] 

oldTuple[::2] 的含义:获取 oldtuple 从开始(值被省略)到结束(被省略)的副本,spepwidth 为 2。