我的任务是编写代码以找到列表的第一个中点和最后一个元素。如果列表长度为1,则该函数必须返回作为列表的第一个媒介,最后一个元素作为列表的唯一元素。如果列表的长度是偶数,则中等元素是列表的((n / 2)– 1)位置
如果mylist = ['Nick',5.8,107,['knife','gun']](长度均匀)第一个=尼克,中= 5.8,最后= ['knife','gun']如果mylist = ['Nick',5.8,107,['knife','gun'],12](奇数长度)第一名=尼克,中= 107,最后= 12
我已经开始编写以下代码。在if ... else中,有2个替代方法可以找到结果
但是尝试时出现以下错误
File "main.py", line 3
if len(mylist) == 1
^
SyntaxError: invalid syntax
我想念什么?
这是我的尝试
mylist = ['Nick', 5.8, 107, ['knife', 'gun']]
def FML(mylist): ## definition of First Medium Last function (FML)
if len(mylist) == 1
res = [ mylist[0], mylist[0], mylist[0]]
print ("The first, last and the medium element of list are : " + str(res))
else
if (len(mylist) % 2) == 0 # list size even
res = [ mylist[0], mylist[-1], mylist[int((len(mylist)/2) - 1)] ] # list slicing
res = mylist[::len(mylist)-1], mylist[int((len(mylist)/2) - 1)] ] # list indexing
print ("The first, last and the medium element of list are : " + str(res))
else # list size odd
res = [ mylist[0], mylist[-1], mylist[int(len(mylist)/2) ] ] # list slicing
res = mylist[::len(alist)-1], mylist[int(len(mylist)/2)] # list indexing
print ("The first, last and the medium element of list are : " + str(res))
我简化了您的代码。即使列表的长度为1,索引-1也会返回与第一个值相同的最后一个值。我还在您的代码中合并了整数除法(//
)以清除其他if-else语句。
def FML(mylist):
res = [mylist[0], mylist[len(mylist)//2], mylist[-1]]
print("The first, last and the medium element of list are : " + str(res))
但是,您的代码的原始问题是由于使用if条件在孤行上缺少了冒号。