python列表问题

已知有序列表

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

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

如:已经get post/2,怎么获取列表中前一项post/1和后一项post/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')]
  • python里面除了import还有什么引入类的方法?
  • 关于PHP框架中的ORM组件的性能问题
  • 关于Python的问题 关于Python的问题
  • Django rest-framework 关联表内容没有显示
  • python中list数据类型转换
  • Flask如何获取客户端提交过来的数据
  • Python标准库中关于bytearray.fromhex(string)的疑问
  • matplotlib图表的背景颜色
  • 使用pip freeze 和 pip freeze –all 和 pip list的区别?
  • 抓包只抓到json,真实的地址却找不到
  • 用过 H-ui 的 ,来看一下