python选取数组中任意位置的相邻元素
比方说有一个排行榜(假设小于1000),需要选取出某个用户的相邻排名前两名和后两名;如果该用户本身没有前两名则在后两名中补齐(比如用户如果是第一名那么去2,3,4,5名),反之同理,用python实现。代码如下,感觉挺笨,不过达到了效果:
假设一共0~14 15个数,输入任意0~14的数以及scope(如果显示前后两名则写4,奇数情况暂没考虑)
Pasting code; enter '--' alone on the line to stop.
: def t(selfid, scope):
: arr = range(15)
: l = len(arr)
: ind = arr.index(selfid)
:
: start = ind - scope/2
: end = ind + scope/2
: if start <= 0:
: end = end - start
: start = 0
: elif end >= l:
: start = start - (end - l) - 1
: end = l
:
: res = arr
: res.remove(selfid)
: return res
:--
测试代码如下:
for i in range(15):
print i, t(i, 4), i in t(i,4)
print '--------------------------'
....:
....:
0 False
--------------------------
1 False
--------------------------
2 False
--------------------------
3 False
--------------------------
4 False
--------------------------
5 False
--------------------------
6 False
--------------------------
7 False
--------------------------
8 False
--------------------------
9 False
--------------------------
10 False
--------------------------
11 False
--------------------------
12 False
--------------------------
13 False
--------------------------
14 False
--------------------------
欢迎拍砖,chop地址:http://chopapp.com/#s5jknzbm
页:
[1]