扫码关注官方订阅号
小伙看你根骨奇佳,潜力无限,来学PHP伐。
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')]
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
python3
list.index 并不可靠,如果list中有重复元素的话,返回的结果就不完整
改进~