[英]Cannot get 1st and 2nd element of a list
I'm trying to write a function definition that takes a sequence and returns the first and second values.我正在尝试编写一个函数定义,它接受一个序列并返回第一个和第二个值。 I suspect my code is wrong because it can't take in a list, but I'm not sure.
我怀疑我的代码是错误的,因为它不能包含在列表中,但我不确定。 Here's my goal:
这是我的目标:
Write a function definition named first_and_second that takes in sequence and returns the first and second value of that sequence as a list.
编写一个名为 first_and_second 的函数定义,它按顺序接收该序列的第一个和第二个值作为列表返回。
Here's the code I'm having trouble with:这是我遇到问题的代码:
def first_and_second(list):
return list[0 and 1]
Here's the test of whether I got it right:这是我是否做对的测试:
assert first_and_second([1, 2, 3, 4]) == [1, 2]
assert first_and_second(["python", "is", "awesome"]) == ["python", "is"]
There's nothing wrong with how your function " takes in a list ", but there's something wrong with how you use the passed list.您的函数“接收列表”的方式没有任何问题,但是您使用传递的列表的方式有问题。
return list[0 and 1]
The expression 0 and 1
evaluates to 0
:表达式
0 and 1
计算结果为0
:
>>> 0 and 1
0
So that code effectively becomes:因此该代码有效地变为:
return list[0]
which will only return the 1st element.这只会返回第一个元素。 What you want to do is called slicing , which means getting a subset of a list.
您想要做的称为slicing ,这意味着获取列表的子集。 From this SO post on Understanding slice notation :
从这个关于理解切片符号的SO帖子:
a[start:stop] # items start through stop-1 a[start:] # items start through the rest of the array a[:stop] # items from the beginning through stop-1 a[:] # a copy of the whole array
The correct code is:正确的代码是:
def first_and_second(aList):
return aList[0:2]
which means " get the elements of aList
from the index=0 element (the first value) up to the index=1 element (the second value) ".这意味着“从 index=0 元素(第一个值)到 index=1 元素(第二个值)获取
aList
的元素”。
>>> def first_and_second(list):
... return list[0:2]
>>> print( first_and_second([1, 2, 3, 4]) == [1, 2] )
True
>>> print( first_and_second(["python", "is", "awesome"]) == ["python", "is"] )
True
Also, note that I changed the function parameter list
to aList
.另请注意,我将函数参数
list
更改为aList
。 DO NOT name your parameters/variables as list
because that is a built-in type in Python.不要将您的参数/变量命名为
list
因为这是 Python 中的内置类型。
def first_and_second(list):
return [list[0],list[1]]
or或者
def first_and_second(list):
return list[0:2]
For a more concise solution, you can use lambda notation:要获得更简洁的解决方案,您可以使用 lambda 表示法:
first_and_second = lambda l : l[:2]
It requires only one keyword instead of two and may therefore be considered a more pythonic way of doing simple things like this.它只需要一个关键字而不是两个关键字,因此可能被认为是一种更像 Python 的方式来做这样的简单事情。
Since the lambda statement above actually is a function defition, you can just use it as follows:由于上面的 lambda 语句实际上是一个函数定义,您可以按如下方式使用它:
assert first_and_second([1, 2, 3, 4]) == [1, 2]
assert first_and_second(["python", "is", "awesome"]) == ["python", "is"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.