逐渐整理python自带函数的用法,自己踩过的一些坑
¶列表插入
- append
将一个数据项添加进列表,如果是列表仍然显示为列表,效率比insert要快很多
- extend
可以将一个新列表的数据以单个元素的形式添加进去
- insert
定义插入位置,insert(1,‘DC’) 在第二个位置前插入
- +
将列表的东西加入进去
¶list to str
如果需要将str与list打印在一起,用+
,前提是将list转为str先
1 | " ".join(['I', 'Love', 'You']) |
1 | ### key 还可以是operator里的itemgetter()、attrgetter() |
1 | ## reverse |
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/