2017-04-14 26 views
0
n = 2 
list1 = [1,4,6,2,8,9,90] 

我怎么会事先去寻找数字与存储上述号码nlist1并存储在变量list1_result如何查找列表中的上一个元素?

+1

欢迎堆栈溢出!请您详细说明您迄今为止所尝试解决您的问题? Stack Overflow社区希望帮助您用_your_代码解决特定的编程问题,但不会为您编写代码。所以,请解释你到目前为止所尝试的。 – Jens

回答

0

这应该工作:

List1 = [1,4,6,2,8,9,90] 
n = 2 
ind = List1.index(n) 
list1_result = List1[ind-1] # is 6 
0

您可以找到号码的索引列表中,然后用它来找到以前的元素:

lst = [1,4,6,2,8,9,90] 
the_index = lst.index(n) 
lst2 = lst[the_index-1] 

现在,你有新的列表存储在lst2中

0

您需要在列表中找到n的索引,然后减去1以获取元素之前的位置。

n = 2 
List1 = [1,4,6,2,8,9,90] 
prev_elem = List1[List1.index(n) - 1] 
0

你可以写,这将通过您的浏览列表,并返回所需的数字,如果找到了一个匹配n 功能试试这个:

def find_previous(List1, n): 
    for i in range(len(List1)): 
     if List1[i] == n and i > 0: 
      return List1[i-1] 
    return None