繁体   English   中英

如何通过在函数中指定特定的整数来返回列表的索引?

[英]How do I return the index of a list by giving it a specific integer in a function?

我的任务之一是编写一个函数,该函数接受两个参数(一个列表和一个整数),并返回列表的指定元素。 因此,例如,如果给它一个列表x和数字2,它将返回列表x的第二个元素。 我的老师希望我们不使用任何列表方法来执行此操作。 但是,这些参数似乎无法通过。 有什么方法可以声明一个变量,然后再对其进行初始化? 我不知道该如何解决。

myList = [1, 3, 'hello', 6, 8]

int num

def find_element(myList, num):
    return myList[num]
print(myList[num])
myList = [1,3,'hello',4,5,6,7]

def find_element(List, Num):
    return List[Num-1]
print(find_element(myList,2)) #Num will print what is contained in list in order
list1 = [1, 3, 'hello', 6, 8]
list2 = [4, 7, 'prevyet', 1, 'a']
list3 = [-99, 77, 'caio', 78, 3]

def find_element(theList, theNum):
    retVal = None
    if theNum >=0 and theNum < len(theList):
        retVal = theList[theNum]
    return retVal

print(find_element(list1, 3))
print(find_element(list2, 0))
print(find_element(list3, 4))

您可以要求用户通过Python 3中的input() [或Python 2中的raw_input() ]输入值。
您可以将其用作检索的索引。 但是该输入确实以字符串形式出现,因此您必须将其转换为整数。 您可以执行以下操作:

def find_element(myList, num):
    return myList[num]

myList = [1, 3, 'hello', 6, 8]

val = input('Please enter an index between 0 and 4: ')
num = int(val)

print(find_element(myList, num))

请注意,您已编写函数以使用与主程序中相同的变量名。 没关系,但是关于正在发生的事情可能会有些混乱。 您可以(可能应该)使用不同的变量名称,以使其更清楚地了解正在发生的事情。 因此,例如,您可以执行以下操作:

def find_element(someList, someNum):
    return someList[someNum]

如您所说,它不能使用任何列表方法。 也许应该使用循环。

def func(arr, num):
    for key, value in enumerate(arr):
        if key == num:
            return value
    return None

my_list = [1, 3, 'hello', 6, 8]
print(my_list, 2)

如果要输入数字。 就像@ Gary02127所说的。

num = int(input("input the number: "))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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