python笔记-list and dict
来源:互联网 发布:淘宝内部优惠券赚佣金 编辑:程序博客网 时间:2024/05/16 11:35
List Methods
Here are some other common list methods.
- list.append(elem) – adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
- list.insert(index, elem) – inserts the element at the given index, shifting elements to the right.
- list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
- list.index(elem) – searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use “in” to check without a ValueError).
- list.remove(elem) – searches for the first instance of the given element and removes it (throws ValueError if not present)
- list.sort() – sorts the list in place (does not return it). (The sorted() function shown below is preferred.)
- list.reverse() – reverses the list in place (does not return it)
- list.pop(index) – removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).
Notice that these are methods on a list object, while len() is a function that takes the list (or string or whatever) as an argument.
list = ['larry', 'curly', 'moe'] list.append('shemp') ## append elem at end list.insert(0, 'xxx') ## insert elem at index 0 list.extend(['yyy', 'zzz']) ## add list of elems at end print list ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz'] print list.index('curly') ## 2 list.remove('curly') ## search and remove that element list.pop(1) ## removes and returns 'larry' print list ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']
Common error: note that the above methods do not return the modified list, they just modify the original list.
list = [1, 2, 3] print list.append(4) ## NO, does not work, append() returns None ## Correct pattern: list.append(4) print list ## [1, 2, 3, 4]
Python Sorting
As another example, specifying “str.lower” as the key function is a way to force the sorting to treat uppercase and lowercase the same:
## "key" argument specifying str.lower function to use for sorting print sorted(strs, key=str.lower) ## ['aa', 'BB', 'CC', 'zz']You can also pass in your own MyFn as the key function, like this: ## Say we have a list of strings we want to sort by the last letter of the string. strs = ['xc', 'zb', 'yd' ,'wa'] ## Write a little function that takes a string, and returns its last letter. ## This will be the key function (takes in 1 value, returns 1 value). def MyFn(s): return s[-1] ## Now pass key=MyFn to sorted() to sort by the last letter: print sorted(strs, key=MyFn) ## ['wa', 'zb', 'xc', 'yd']
To use key= custom sorting, remember that you provide a function that takes one value and returns the proxy value to guide the sorting. There is also an optional argument “cmp=cmpFn” to sorted() that specifies a traditional two-argument comparison function that takes two values from the list and returns negative/0/positive to indicate their ordering. The built in comparison function for strings, ints, … is cmp(a, b), so often you want to call cmp() in your custom comparator. The newer one argument key= sorting is generally preferable.
Dict Formatting
The % operator works conveniently to substitute values from a dict into a string by name:
hash = {} hash['word'] = 'garfield' hash['count'] = 42 s = 'I want %(count)d copies of %(word)s' % hash # %d for int, %s for string # 'I want 42 copies of garfield'
Del
The “del” operator does deletions. In the simplest case, it can remove the definition of a variable, as if that variable had not been defined. Del can also be used on list elements or slices to delete that part of the list and to delete entries from a dictionary.
var = 6 del var # var no more! list = ['a', 'b', 'c', 'd'] del list[0] ## Delete first element del list[-2:] ## Delete last two elements print list ## ['b'] dict = {'a':1, 'b':2, 'c':3} del dict['b'] ## Delete 'b' entry print dict ## {'a':1, 'c':3}
Files
The open() function opens and returns a file handle that can be used to read or write a file in the usual way. The code f = open(‘name’, ‘r’) opens the file into the variable f, ready for reading operations, and use f.close() when finished. Instead of ‘r’, use ‘w’ for writing, and ‘a’ for append. The special mode ‘rU’ is the “Universal” option for text files where it’s smart about converting different line-endings so they always come through as a simple ‘\n’. The standard for-loop works for text files, iterating through the lines of the file (this works only for text files, not binary files). The for-loop technique is a simple and efficient way to look at all the lines in a text file:
# Echo the contents of a file f = open('foo.txt', 'rU') for line in f: ## iterates over the lines of the file print line, ## trailing , so print does not add an end-of-line char ## since 'line' already includes the end-of line. f.close()
Reading one line at a time has the nice quality that not all the file needs to fit in memory at one time – handy if you want to look at every line in a 10 gigabyte file without using 10 gigabytes of memory. The f.readlines() method reads the whole file into memory and returns its contents as a list of its lines. The f.read() method reads the whole file into a single string, which can be a handy way to deal with the text all at once, such as with regular expressions we’ll see later.
For writing, f.write(string) method is the easiest way to write data to an open output file. Or you can use “print” with an open file, but the syntax is nasty: “print >> f, string”. In python 3000, the print syntax will be fixed to be a regular function call with a file= optional argument: “print(string, file=f)”.
Files Unicode
The “codecs” module provides support for reading a unicode file.
import codecs
f = codecs.open('foo.txt', 'rU', 'utf-8')for line in f: # here line is a *unicode* string
For writing, use f.write() since print does not fully support unicode.
- python笔记-list and dict
- Python笔记--String、list、dict排序
- sort list and dict
- list and dict
- python dict list
- 【python】-list,tuple,dict
- python list与dict
- Python:list,tuple,dict
- [Python]list, tuple,dict
- Python:list、dict、string
- Python list dict iteration
- Python----list,dict,tuple
- Python-dict AND set
- Python学习笔记--表list, 元组tuple, 字典dict
- Python入门笔记(3)_ List, Tuple, Dict, Set
- Python学习笔记:讲两个list合并成字典dict
- Python笔记-list、tuple、dict、set及其比较
- Python学习笔记---元组(tuple)、列表(list)、字典(dict)
- 活动选择问题
- springboot 集成 mybatis
- 11. Container With Most Water
- caffe代码阅读7:Caffe中卷积的实现
- A1067. Sort with Swap(0,*) (25)
- python笔记-list and dict
- 跨域
- mysql存储过程(后台学习之路六)
- 前端开源项目周报0207
- 学习vue.js心得
- 高并发解决方案——提升高并发量服务器性能解决思路
- 编程学习
- 轻松看懂机器学习十大常用算法
- 【设计模式】【八】外观模式