python列表问题

已知有序列表

posts=['post/1','post/2','post/3']

现在已经知道post(posts列表中任意值,如post/1),怎么这个post,来获取post[-1]和post[1]的值

如:已经get post/2,怎么获取列表中前一项post/1和后一项post/3

阅读 2.7k
3 个回答
posts = ['post/1', 'post/2', 'post/3']
know_string = 'post/2'
know_string_index = posts.index(know_string)

#the forward string
forward_string = None if know_string_index == 0 else posts[know_string_index - 1]
print(forward_string)

#the back string
back_string = None if know_string_index == length(posts) else posts[know_string_index + 1]
print(back_string)
# python 2.7
def get_around_post(post, posts):
    lpost, rpost = None, None
    if post in posts:
        length = len(posts)
        idx = posts.index(post)
        lpost = None if idx < 1 else posts[idx-1]
        rpost = None if idx > length-2 else posts[idx+1]
    else:
        print 'Not find post[%s] in post%s' % (post, posts)
    return lpost, rpost

# test
posts = ['post/1', 'post/2', 'post/3']
print get_around_post('post/1', posts)
print get_around_post('post/2', posts)
print get_around_post('post/3', posts)

python3

>>> def around(c,ls):
    i=ls.index(c)
    return i,ls[(i-1)],ls[(i+1)%len(ls)]

>>> ls=['a','b','c','d','e',]
>>> around('a',ls)
(0, 'e', 'b')
>>> around('e',ls)
(4, 'd', 'a')
>>> around('c',ls)
(2, 'b', 'd')
>>> 

list.index 并不可靠,如果list中有重复元素的话,返回的结果就不完整

改进~

>>> def around(c,ls,cyclic=True):
    S,ln = -1,len(ls)
    ret=[]
    for x in range(ls.count(c)):
        S = i = ls.index(c,S+1)
        ret.append((i,
                ls[(i-1)] if cyclic or i>0 else None,
                ls[(i+1)%ln] if cyclic or i<ln-1 else None))
    return ret

>>> ls = ['a', 'b', 'c', 'd', 'e', 'c']
>>> around('a',ls,False)
[(0, None, 'b')]
>>> around('c',ls,False)
[(2, 'b', 'd'), (5, 'e', None)]
>>> around('a',ls)
[(0, 'c', 'b')]
>>> around('c',ls)
[(2, 'b', 'd'), (5, 'e', 'a')]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题