已知有序列表
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']
现在已经知道post(posts列表中任意值,如post/1),怎么这个post,来获取post[-1]和post[1]的值
如:已经get post/2,怎么获取列表中前一项post/1和后一项post/3
# 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')]
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
1 回答3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.5k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决