# 列表骚操作

## 统计列表重复项数量并排序

* **题目概述** 对于一个列表，比如List = \[1,2,3,4,5,3,2,1,4,5,6,4,2,3,4,6,2,2]，现在我们需要统计这个列表中的重复项，统计出重复次数后，按照我们自己的要求进行排序。

### 统计重复项出现次数

方法一：

```python
List = [1,2,3,4,5,3,2,1,4,5,6,4,2,3,4,6,2,2]
List_set = set(List) #List_set是另外一个列表，里面的内容是List里面的无重复 项
for item in List_set:
print("the %d has found %d" %(item,List.count(item)))
```

方法二：（利用字典的特性来实现）

```python
List=[1,2,3,4,5,3,2,1,4,5,6,4,2,3,4,6,2,2]
a = {}
for i in List:
    if List.count(i)>1:
        a[i] = List.count(i)
        a = sorted(a.items(), key=lambda item:item[0])
print (a)
```

方法三：内置函数

```python
from collections import Counter
List=[1,2,3,4,5,3,2,1,4,5,6,4,2,3,4,6,2,2]
c = Counter(list)
c.values()
sum(c.values())
c.keys()
c.clear()
list(c)
set(c)
dict(c)
c.items()
c += Counter()    #这个是最神奇的，就是可以将负数和0的值对应的key项去掉
```

方法四：（只用列表来进行实现）

```python
List=[1,2,3,4,5,3,2,1,4,5,6,4,2,3,4,6,2,2]
count_times = []
for i in l :
    count_times.append(l.count(i))
m = max(count_times)
n = l.index(m)
print (list[n])
```

实现原理：把列表中的每一个数出现的次数在其对应的位置上记录下来，然后用max求出出现次数最多的位置。但有一个缺点，如果有多个结果，最后的实现结果只是出现在最左边的那个上，不过要改进也很简单，感兴趣的同学可以想一下如何解决这个小bug！

先简单介绍一下sorted()函数：

> sorted(iterable,key,reverse)，sorted一共有iterable,key,reverse这三个参数。 其中iterable表示可以迭代的对象，例如可以是dict.items()、dict.keys()等，key是一个函数，用来选取参与比较的元素，reverse则是用来指定排序是倒序还是顺序，reverse=true则是倒序，reverse=false时则是顺序，默认时reverse=false。 特别注意：在按值排序的过程中，item是items中的一个元素，这里就是固定用item，而不是用字典dic

```python
按照键（key）进行排序

升序：
dic = {'a':15, 'e':13, 'd':45, 'b':10}
dic = sorted(dic.items(), key = lambda dic:dic[0])
print(dic)

降序：
dic = {'a':15, 'e':13, 'd':45, 'b':10}
dic = sorted(dic.items(), key = lambda dic:dic[0] reverse = True)
print(dic)

按照值（value）进行排序
升序：
dic = {'a':15, 'e':13, 'd':45, 'b':10}
dic = sorted(dic.items(), key = lambda item:item[1])
print(dic)
降序：
dic = {'a':15, 'e':13, 'd':45, 'b':10}
dic = sorted(dic.items(), key = lambda item:item[1] reverse = True)
print(dic)
```

### for循环取指定数量元素

```python
lis = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

从lis中每次取两个元素,且所取不重复:

```python
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
```

方法一：

```python
ret = []

a =  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for i in range(0,len(a), 2):
    ret.append(a[i:i+2])
    print(a[i:i+2])

# [1, 2]
# [3, 4]
# [5, 6]
# [7, 8]
# [9, 10]
```

方法二：

```python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for r in [a[i:i + 2] for i in range(0, len(a), 2)]:  # 列表生成式
    print(r)

# [1, 2]
# [3, 4]
# [5, 6]
# [7, 8]
# [9, 10]
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/python/python-xiao-ji-qiao/lie-biao-sao-cao-zuo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
