简体   繁体   English

递归搜索列表列表并返回原始列表中的索引位置

[英]Search through List of list recursively and return index position in original list

Title says most of the problem. 标题说明了大部分问题。 WE ARE REQUIRED TO WRITE THIS RECURSIVELY . 我们需要递归地写这个 We are given a list of presidents: 我们得到了总统名单:

    preslst=[['George Washington',1732,1788],['John Adams',1735,1796],['Thomas Jefferson',1743,1800],['James Madison',1751,1808],
     ['James Monroe',1758,1816],['John Quincy Adams',1767,1824],['Andrew Jackson',1767,1828],['Martin Van Buren',1782,1836],
     ['William Henry Harrison',1773,1840],['John Tyler',1790,1840],['James K. Polk',1795,1844],['Zachary Taylor',1784,1848],
  ['Millard Fillmore',1800,1850],['Franklin Pierce',1804,1858],['James Buchanan',1791,1857],['Abraham Lincoln',1809,1861],
     ['Andrew Johnson',1808,1865],['Ulysses S. Grant',1822,1869],['Rutherford B. Hayes',1822,1877],['James A. Garfield',1831,1881],
     ['Chester A. Arthur',1829,1881],['Grover Cleveland',1837,1885],['Benjamin Harrison',1833,1889],['Grover Cleveland',1837,1893],
     ['William McKinley',1843,1897],['Theodore Roosevelt',1858,1901],['William Howard Taft',1857,1909],['Woodrow Wilson',1856,1913],
     ['Warren G. Harding',1865,1921],['Calvin Coolidge',1872,1923],['Herbert Hoover',1874,1929],['Franklin D. Roosevelt',1882,1933],
     ['Harry S. Truman',1884,1945],['Dwight D. Eisenhower',1890,1953],['John F. Kennedy',1917,1961],['Lyndon B. Johnson',1908,1963],
     ['Richard M. Nixon',1913,1969],['Gerald Ford',1913,1974],['Jimmy Carter',1924,1977],['Ronald Reagan',1911,1981],
     ['George H. Bush',1924,1989],['Bill Clinton',1946,1993],['George H.W. Bush',1946,2001],['Barack Obama',1961,2009],
     ['Donald Trump',1946,2017]]

We are asked to define a function (arg1 = presidents name as formatted in the list, arg2 = preslst) that will recursively go through the list and return the index position of the list that holds the right name. 我们被要求定义一个函数(arg1 =列表中格式的行长名称,arg2 = preslst),该函数将递归遍历该列表并返回包含正确名称的列表的索引位置。

This is what I have currently: 这是我目前拥有的:

def presPosition(pres,preslst):
    for i in range(0,len(preslst)):
        print('search')
        presname = preslst[i][0]

        if presname ==  pres:
            print("FOUND")
            foundpres = preslst[0]
            return preslst.index(foundpres)

        else:
            return presPosition(pres,preslst[1:]) 

Ex: presPosition('John Adams',preslst) the returned value should be 1. 例如:presPosition('John Adams',preslst)返回值应为1。

I keep getting 0 as the returned value, and I understand why because the preslst being passed in the else statement will have the name I'm looking for as the first item in the passed list. 我一直将0用作返回值,并且我理解为什么,因为在else语句中传递的preslst将具有我要查找的名称,作为传递列表中的第一项。 So how do I get the function to return the position of the where it is in the original list? 那么,如何获取该函数以返回其在原始列表中的位置呢?

Thanks in advance. 提前致谢。

Try the below if you need recursion. 如果您需要递归,请尝试以下方法。

def presPosition(pres, preslst, i=0):
    if i == len(preslst):
        return "Pres Not Found!"

    if preslst[i][0] == pres:
        return i
    else:

        return presPosition(pres, preslst, i+=1)

In your code, you are removing the first element, therefore your index will always be 0. 在您的代码中,您将删除第一个元素,因此您的索引将始终为0。

This is how to do it with enumerate() and a for-loop : 这是如何使用enumerate()for-loop

 def myFunc(pname, plist)    
    presname = pname
    preslist = plist
    for index, tup in enumerate(plist):
        if tup[0] == pname:
            return index
        raise ValueError('value not found in list')

This is a weird exercise and definitely not fit for recursion. 这是一个奇怪的练习,绝对不适合递归。 However, here's something you could do. 但是,您可以执行以下操作。 Return the length of the list when you find the element and at the end you subtract it from the original list's size: 找到元素后返回列表的长度,最后从原始列表的大小中减去它:

def presPosition(pres,preslst):
    print('search')
    presname = preslst[0][0]

    if presname ==  pres:
        print("FOUND")
        return len(preslst)

    else:
        return presPosition(pres,preslst[1:])

preslst = [...] # your list
print(len(preslst) - presPosition('James Madison', preslst)) # outputs 3

BTW, you don't need the for loop as you're only using the first element and then returning, so I removed it. 顺便说一句,您不需要for循环,因为您只使用第一个元素然后返回,因此我将其删除。

You are getting 0 because after each iteration you pass preslst[1:] to the next iteration. 之所以得到0是因为在每次迭代之后,您将preslst[1:]传递给下一个迭代。 And you return preslst.index(foundpres) which is from the above list and its always the 0th index. 然后返回preslst.index(foundpres) ,它来自上面的列表,并且始终是第0个索引。

Instead I suggest follow. 相反,我建议遵循。

def presPosition(pres,preslst, next_index=0):
    print('search')
    if next_index == len(preslst):
        print("NOT FOUND")
        return

    presobj = preslst[next_index]
    presname = presobj[0]

    if presname ==  pres:
        print("FOUND")
        return preslst.index(presobj)    # return next_index

    else:
        return presPosition(pres,preslst, next_index+1)

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

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