通过向函数传递变量,从列表中提取索引值

时间:2015-01-30 19:50:41

标签: python

我试图根据传递给函数的变量获取list的索引值。我用硬编码来说明正确的结果。因此,'邻居'应该返回先前的邮政编码,输入的邮政编码和下一个邮政编码(总共3个邮政编码)。

def foo(zip):
    zipcodes = [11105,11102,11103,11104,11377,11373,11372,11368]
    neighbors = []
    if zip in zipcodes:
  #     x = "index of zip"
  #     num = zipcodes[x]  --> i.e. x = 4
        num1 = 4-1 # x - 1
        num2 = 4+2 # x + 2
        neighbors = zipcodes[num1:num2] 
        print neighbors

foo(11377)

2 个答案:

答案 0 :(得分:0)

您可以使用以下功能:

>>> def foo(zip,zipcodes):
...     x=zipcodes.index(zip)
...     if x==0 :
...       return zipcodes [:2]
...     elif x==len(zipcodes):
...       return zipcodes [-2:]
...     return zipcodes[x-1:x+2]
... 
>>> zipcodes = [11105,11102,11103,11104,11377,11373,11372,11368]
>>> foo(11105,zipcodes)
[11105, 11102]
>>> foo(11368,zipcodes)
[11372, 11368]
>>> foo(11104,zipcodes)
[11103, 11104, 11377]

答案 1 :(得分:0)

您非常接近解决方案,只需使用list.index(element)

找到合适的索引
def foo(zip):
    zipcodes = [11105,11102,11103,11104,11377,11373,11372,11368]
    neighbors = []
    if zip in zipcodes:
        x = zipcodes.index(zip)
        num1 = x-1 
        num2 = x+2 
        # ensure that idx doesn't get -1
        if num1<0: num1=0 
        neighbors = zipcodes[num1:num2] 
        print neighbors
foo(11377)

编辑:还要确保,你的num1-idx没有得到-1,因为这不会产生正确的结果。