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

时间:2019-12-09 22:35:24

标签: python list function sequence

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

  

编写一个名为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"]

3 个答案:

答案 0 :(得分:1)

函数“ 获取列表”没有什么错,但是使用传递的列表却有问题。

return list[0 and 1]

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

>>> 0 and 1
0

因此该代码有效地变为:

return list[0]

,它将仅返回第一个元素。您要执行的操作称为slicing,这意味着获取列表的子集。在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

正确的代码是:

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中是built-in type

答案 1 :(得分:0)

Abiraterone acetat from L253
<h1 class="title" id="page-title"><span class="ca-gov-icon-arrow-down"></span> Abiraterone acetate </h1>

A CYP17 inhibitor indicated in combination with prednisone for the treatment of patients with metastatic castration-resistant prostate cancer
from L265
<h3 class="label-above">Occurence(s)/Use(s)</h3><p>A CYP17 inhibitor indicated in combination with prednisone for the treatment of patients with metastatic castration-resistant prostate cancer.</p>

02/02/2016 from L266
<h3 class="label-above">Date Added</h3><span class="date-display-single" property="dc:date" datatype="xsd:dateTime" content="2016-02-02T00:00:00-08:00">02/02/2016</span>  </div>

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

答案 2 :(得分:0)

要获得更简洁的解决方案,可以使用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"]