问题描述:
Input: A tuple, at least 3 elements long.
Output: A tuple.
def easy_unpack(elements: tuple) -> tuple:
"""
returns a tuple with 3 elements - first, third and second to the last
"""
# your code here
return ()
if __name__ == '__main__':
print('Examples:')
print(easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)) == (1, 3, 7)
assert easy_unpack((6, 2, 9, 4, 3, 9)) == (6, 9, 3)
assert easy_unpack((1, 1, 1, 1)) == (1, 1, 1)
assert easy_unpack((6, 3, 7)) == (6, 7, 3)
print('Done! Go Check!')
一个最基础的索引问题,可以直接返回第一、第三和倒数第二位置的元素。
return (elements[0],elements[2],elements[-2])
思考:
来自其他用户的解决方案。
方案一:for 循环
def easy_unpack(elements):
"""
returns a tuple with 3 elements - first, third and second to the last
"""
return tuple(elements[i] for i in [0,2,-2])
class tuple
([iterable])
可以用多种方式构建元组:
-
使用一对圆括号来表示空元组:
()
-
使用一个后缀的逗号来表示单元组:
a,
或(a,)
-
使用以逗号分隔的多个项:
a, b, c
or(a, b, c)
-
使用内置的
tuple()
:tuple()
或tuple(iterable)
所以如果直接返回一个元组,应该会更加严谨一点。
有时候看别人的回答,真的会给自己一个不一样的思路。