python 自带函数

逐渐整理python自带函数的用法,自己踩过的一些坑

列表插入

  1. append

将一个数据项添加进列表,如果是列表仍然显示为列表,效率比insert要快很多

  1. extend

可以将一个新列表的数据以单个元素的形式添加进去

  1. insert

定义插入位置,insert(1,‘DC’) 在第二个位置前插入

  1. +

将列表的东西加入进去

list to str

如果需要将str与list打印在一起,用+,前提是将list转为str先

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
" ".join(['I', 'Love', 'You'])

## or string.join, default separator is a single space

import string
string.join(list, sep=',')

## the third way?

```py
## 排序

* 需要copy的使用b = sorted(a)
* 修改原来的列表用 a.sort(), 这时候回返回`None`,a已经修改

用sorted的例子

```py
## key
### key可以用长度,str.lower 或者 自定义filter
a = [{'name':'abc','age':20},{'name':'def','age':30},{'name':'ghi','age':25}]

def age(s):
return s['age']
sorted(a, key = age)

f2 = sorted(f, key = lambda x : x['age'])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
### key 还可以是operator里的itemgetter()、attrgetter() 
from operator import itemgetter, attrgetter
class Student:
def init(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def repr(self):
return repr((self.name, self.grade, self.age))

student_objects = [
Student('zzz', 'A', 25),
Student('xxx', 'A+', 20)
]

sorted(student_objects, key = itemgetter(2))
sorted(student_objects, key = attrgetter('age'))

## 多级排序
sorted(students_objects, key = itemgetter(2,1))

## 相同记录排序,保留原来的顺序
1
2
## reverse
sorted(a, reverse = True)

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).

sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you’ll get the keys), generators, etc., returning a list containing all elements, sorted.

Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable, not a list yet.
For lists, list.sort() is faster than sorted() because it doesn’t have to create a copy. For any other iterable, you have no choice.
No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.

TBC

reference: http://python.jobbole.com/85488/