2016-05-14 72 views
0

我期待着巩固一个我知道可以改进的功能。动态搜索python列表

我有一系列全局列表,我将其添加到列表中,并定期添加列表数。

在此函数中,我可以搜索输入字符并返回列表中的列表号和位置。不幸的是,每次我添加一个新列表时,我还必须添加一个新的嵌套try /除ValueError以及新的列表名称。

我确信有人比我有更多的编码经验可以想出一种递归调用此函数和搜索的方式,而不嵌套这些。 理想情况下,我想我会指定有多少“Listx”列表使用接受字符串和整数的函数进行搜索?

def findInLists(inputString): 

    line = 0 
    output = 0 

    try: 
     output = List1.index(inputString) 
    except ValueError: 
     line += 1 
     try: 
      output = List2.index(inputString) 
     except ValueError: 
      line += 1 
      try: 
       output = List3.index(inputString) 
      except ValueError: 
       line += 1 
       try: 
        output = List4.index(inputString) 
       except ValueError: 
        output = -1 
    return str(line) + str(output) 
+0

有关使用嵌套列表是什么? – Leva7

+0

你的意思是输出= List.index(inputString)被输出= List2.index(inputString) – PyNEwbie

回答

0

修改 - 所以你愿意在搜索之前指定列表的固定数量:

def _search_lists(phrase,numb_of_lists): 
    for n in range(1, numb_of_lists + 1): 
     list_name = "list" + str(n) 
     list_to_search = eval(list_name) 
     if search phrase in list_to_search: 
      return n, list_to_search.index(search_phrase) 
    return 0,0 

返回的是列表号和索引位置,如果不是那么任何列表(0 ,0)

请注意,许多人警告使用eval函数的危险,但在这种情况下,假设它是你的代码,你应该没问题。

+0

这是一个非常干净的方法 - 我没有意识到我可以使用一个字符串来调用我生成的列表。 - 谢谢! –

+0

很久以前我有一个类似的问题http://stackoverflow.com/questions/7748596/can-i-variabalize-an-object-like-a-dictionary-reference-in-python – PyNEwbie

0

如果你只是想避免嵌套,使用早期return S:

def findInLists(inputString): 

    line = 0 
    output = 0 

    try: 
     output = List1.index(inputString) 
     return str(line) + str(output) 
    except ValueError: 
     line += 1 
    try: 
     output = List2.index(inputString) 
     return str(line) + str(output) 
    except ValueError: 
     line += 1 
    try: 
     output = List3.index(inputString) 
     return str(line) + str(output) 
    except ValueError: 
     line += 1 
    try: 
     output = List4.index(inputString) 
     return str(line) + str(output) 
    except ValueError: 
     output = -1 
    return str(line) + str(output) 

现在这仍然是一个很多重复的逻辑,是不是?但现在更容易将其重构为for -loop。您澄清后

0

您实际上想要搜索列表的列表。所以你应该列出一个列表,而不是在变量名上使用后缀。

所以这些方针的东西应该适合你的需求:

def find_it(lists, val): 
    idxVal = -1 
    idxList = -1 
    for l in lists: 
     try: 
      f = l.index(val) 
     except: 
      pass 
    return idxList, idxVal 

listIndex, valueIndex = find_it([List1, List2, List3], "foo") 

当然这只是许多可能的解决方案之一(你可以做到这一点递归,尾部第一,使用reduce(),等等等等)

一般来说,如果你觉得你有许多相同类型的东西,你应该使用列表。后缀变量名称是一种代码味道。

0

我会做这样的事情:

list1= ["foo"]; 
list2= ["foo"]; 
list3= ["foo"]; 
list4= ["foo", "baz"]; 

def findInLists(inputString): 
    lists = [list1, list2, list3, list4]; 
    output = -1; 
    for i, each in enumerate(lists): 
     try: 
      output = each.index(inputString) 
      break 
     except ValueError: 
      pass 
    return str(i+1) + str(output) 

试试看:https://repl.it/CQn3/3