简体   繁体   中英

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. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple'). I got 0.6/1 with this code:

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] . If you leave any of those start , end , or step blank, they default to the beginning, the end, and 1 respectively. 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:

>>> 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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