---
title: "python选取数组中任意位置的相邻元素"
author: "monkeyc"
date: "2011-09-28T13:21:16Z"
tags: []
categories: ["互联网"]
slug: "python"
draft: false
lastmod: "2011-09-28T13:21:16Z"
id: 1182364
url: "https://monkeycc.iteye.com/blog/1182364"
---

比方说有一个排行榜（假设小于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[start:end + 1]
:        res.remove(selfid)
:        return res
:--
```

 测试代码如下：

```
for i in range(15):
    print i, t(i, 4), i in t(i,4)
    print '--------------------------'
   ....:     
   ....:     
0 [1, 2, 3, 4] False
--------------------------
1 [0, 2, 3, 4] False
--------------------------
2 [0, 1, 3, 4] False
--------------------------
3 [1, 2, 4, 5] False
--------------------------
4 [2, 3, 5, 6] False
--------------------------
5 [3, 4, 6, 7] False
--------------------------
6 [4, 5, 7, 8] False
--------------------------
7 [5, 6, 8, 9] False
--------------------------
8 [6, 7, 9, 10] False
--------------------------
9 [7, 8, 10, 11] False
--------------------------
10 [8, 9, 11, 12] False
--------------------------
11 [9, 10, 12, 13] False
--------------------------
12 [10, 11, 13, 14] False
--------------------------
13 [10, 11, 12, 14] False
--------------------------
14 [10, 11, 12, 13] False
--------------------------
```

 

欢迎拍砖，chop地址：[http://chopapp.com/#s5jknzbm](http://chopapp.com/#s5jknzbm)