flask - python列表问题
伊谢尔伦
伊谢尔伦 2017-04-18 10:09:49
[Python讨论组]
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(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)
PHPz
# 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')]
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号