简体   繁体   English

如何将元组作为输入,并将其作为新元组返回,但只能使用奇数?

[英]How to take a tuple as input, and return it as a new tuple, but only with odd numbers?

Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one.编写一个名为oddTuples 的过程,它接受一个元组作为输入,并返回一个新的元组作为输出,其中输入元组的所有其他元素都被复制,从第一个开始。 So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple').因此,如果 test 是元组 ('I', 'am', 'a', 'test', 'tuple'),则在此输入上评估oddTuples 将返回元组 ('I', 'a', 'tuple' )。 I got 0.6/1 with this code:我用这个代码得到了 0.6/1:

def oddTuple(tup):
    b = 1
    if b % 2 != 0:
        d.append(tup[b])
        b += 1
    print (d)

You can do this with basic slicing.你可以用基本的切片来做到这一点。

tup = ('I', 'am', 'a', 'test', 'tuple')
tup[::2]
# ('I', 'a', 'tuple')

The syntax for slicing is iterable[start:end:step] .切片的语法是iterable[start:end:step] If you leave any of those start , end , or step blank, they default to the beginning, the end, and 1 respectively.如果您将startendstep任何一个留空,则它们分别默认为开始、结束和 1。 So the above is going through the whole thing (beginning to end) but only selecting every other element.所以上面的内容贯穿了整个事情(开始到结束),但只选择了其他所有元素。

If you need it in a method:如果您在方法中需要它:

def odd_tuple(tup):
    return tup[::2]  # or print(tup) if you prefer

You can use enumerate and return odd elements as tuple like below:您可以使用enumerate并将奇数元素作为tuple返回,如下所示:

>>> def oddTuple(tup):
...    return tuple(t for idx, t in enumerate(tup) if idx % 2==0)
        
>>> oddTuple(('I', 'am', 'a', 'test', 'tuple'))
('I', 'a', 'tuple')

Try this:尝试这个:

def oddTuple(tup):
    return tuple(tup[i] for i in range(0, len(tup), 2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM