繁体   English   中英

无法获取列表的第一个和第二个元素

[英]Cannot get 1st and 2nd element of a list

我正在尝试编写一个函数定义,它接受一个序列并返回第一个和第二个值。 我怀疑我的代码是错误的,因为它不能包含在列表中,但我不确定。 这是我的目标:

编写一个名为 first_and_second 的函数定义,它按顺序接收该序列的第一个和第二个值作为列表返回。

这是我遇到问题的代码:

def first_and_second(list):
  return list[0 and 1]

这是我是否做对的测试:

assert first_and_second([1, 2, 3, 4]) == [1, 2]
assert first_and_second(["python", "is", "awesome"]) == ["python", "is"]

您的函数“接收列表”的方式没有任何问题,但是您使用传递的列表的方式有问题。

return list[0 and 1]

表达式0 and 1计算结果为0

>>> 0 and 1
0

因此该代码有效地变为:

return list[0]

这只会返回第一个元素。 您想要做的称为slicing ,这意味着获取列表的子集。 从这个关于理解切片符号的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

正确的代码是:

def first_and_second(aList):
  return aList[0:2]

这意味着“从 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

另请注意,我将函数参数list更改为aList 不要将您的参数/变量命名为list因为这是 Python 中的内置类型

def first_and_second(list):
    return [list[0],list[1]]

或者

def first_and_second(list):
    return list[0:2]

要获得更简洁的解决方案,您可以使用 lambda 表示法:

first_and_second = lambda l : l[:2]

它只需要一个关键字而不是两个关键字,因此可能被认为是一种更像 Python 的方式来做这样的简单事情。

由于上面的 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.

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