Help on class list in module __builtin__:
class list(object)| list(iterable) -> new list initialized from iterable's items # 返回一个以迭代器里的所有元素新建的list!以下是例子。
>>> list([1,2,3,4])
[1, 2, 3, 4]
>>> list((1,2,3,4))
[1, 2, 3, 4]
>>> list("1234")
['1', '2', '3', '4']
| Methods defined here:
>>> l = [1, 2, 3, 4, 2, 5, 5, 2, 3, 6]
>>> a = ("a", 1, "dd")
>>> l.extend(a)
>>> l
[1, 2, 3, 4, 2, 5, 5, 2, 3, 6, 'a', 1, 'dd']
| index(...)
# 返回第一个value的下标!如果value不存在,报错!
>>> l
[1, 3, 4, 2, 5, 5, 2, 3, 6, 'a', 1, 'dd']
>>> l.reverse()
>>> l
['dd', 1, 'a', 6, 3, 2, 5, 5, 2, 4, 3, 1]
>>> l.sort()
>>> l
[1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 'a', 'dd']
>>>
>>> queue = ["Eric", "John", "Michael"]
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.pop(0)
'Eric'
>>> queue.pop(0)
'John'
>>> queue
['Michael', 'Terry', 'Graham']
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> seq = range(8)
>>> def square(x): return x*x
...
>>> map(None, seq, map(square, seq))
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55
>>> def sum(seq):
... def add(x,y): return x+y
... return reduce(add, seq, 0)
...
>>> sum(range(1, 11))
55
>>> sum([])
0
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> vec = [2, 4, 6]
>>> [3*x for x in vec]
[6, 12, 18]
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
>>> [[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
>>> [x, x**2 for x in vec] # error - parens required for tuples
File "", line 1, in ?
[x, x**2 for x in vec]
^
SyntaxError: invalid syntax
>>> [(x, x**2) for x in vec]
[(2, 4), (4, 16), (6, 36)]
>>> vec1 = [2, 4, 6]
>>> vec2 = [4, 3, -9]
>>> [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
>>> [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]
为使链表推导式匹配for循环的行为,可以在推导之外保留循环变量:
>>> x = 100 # this gets overwritten
>>> [x**3 for x in range(5)]
[0, 1, 8, 27, 64]
>>> x # the final value for range(5)
4
>>> a = [-1, 1, 66.6, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.6, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.6, 1234.5]
del 也可以用于删除整个变量:
>>> del a
| ----------------------------------------------------------------------
tuple定义注意事项:【更新于:2014.05.22】
>>> t = ("abc")
>>> t
'abc'
>>> t1 = ("abc",)
>>> t1
('abc',)
>>> print type(t), type(t1)
原因是:()既可以表示tuple,又可以是数学公式中的()!所以tuple定义时候记得最后加上, 永不出错!上面代码可以看得出来,显示的时候也是加了,的。
在下列的dict里面会有解释。简单来说:tuple里面可以定义可变的元素list,dict。
>>> t = (11 ,"aa", [22, "bb"], {1:"a", 2: "b"},)
>>> t,type(t)
((11, 'aa', [22, 'bb'], {1: 'a', 2: 'b'}), )
>>> t[2].append(u"可变")
>>> t[3].update({3: "c"})
>>> t[3].pop(1)
'a'
>>> t
(11, 'aa', [22, 'bb', u'\xbf\xc9\xb1\xe4'], {2: 'b', 3: 'c'})
>>>
解释:tuple“不可变”指的是里面的元素不可变,也就是元素指向不变。但指向的东西如上面代码里的第2个位置为list,list可变,所以看起来tuple是可变的。
要保证tuple里面所有东西都不变,则tuple里面的元素不能用可变的list等。
class tuple(object)
| tuple() -> empty tuple # 同list,工厂函数以下关于mapping object的解释来自于:点击打开链接 mapping object把一个可哈希的值(hashable value)映射到一个任意的object上。 什么是可哈希的: 一个object是可哈希的(hashable), 是指这个object在其生存期内有一个不变的哈希值(hash value),即__hash__()方法返回的值。 所有不可变的(immutable)内置object都是hashable的,比如string,不可变的tuple【2014.4.9修订:此处错误,因为tuple可以嵌套list和dict,本质上还是可变的!所以不是所有tulpe都可以作为key!作为key的要求是绝对不可变。所以我强调是不可变的tuple】。所有可变的(mutable)内置容器都不是hashable的,比如list,dict(即没有__hash__()方法)。而所有自定义的类(use-defined class)对象都是可哈希的(hashable),并且只能和自己相等,其hashvalue为其id(object)的值,这里的id()为内置函数,CPython实现的时候取的对象在内存中的地址。 字典Dictionary的key必须是可哈希的,所以tuple,string可以做key,而list不能做key,关于这个我以后会专门解释,或参见https://wiki.python.org/moin/DictionaryKeys。| dict(iterable) -> new dictionary initialized as if via:
>>> for k, v in zip(range(10),range(10, 20)):
print k, v
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
>>> x ={'username' : 'admin', 'machines' : ['foo', 'bar', 'baz']}
>>> y = x.copy()
>>> y
{'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
>>> y["machines"].remove("foo")
>>> y
{'username': 'admin', 'machines': ['bar', 'baz']}
>>> x
{'username': 'admin', 'machines': ['bar', 'baz']}
>>> x["machines"].remove("baz")
>>> x
{'username': 'admin', 'machines': ['bar']}
>>> y
{'username': 'admin', 'machines': ['bar']}
>>> x.pop("username")
'admin'
>>> x
{'machines': ['bar']}
>>> y
{'username': 'admin', 'machines': ['bar']}
>>> y.update({"test": "hello"})
>>> y
{'username': 'admin', 'test': 'hello', 'machines': ['bar']}
>>> x
{'machines': ['bar']}
>>> x.update({"username": "world"})
>>> x
{'username': 'world', 'machines': ['bar']}
>>> y
{'username': 'admin', 'test': 'hello', 'machines': ['bar']}
>>> import copy
>>> x ={'username' : 'admin', 'machines' : ['foo', 'bar', 'baz']}
>>> y = copy.deepcopy(x)
>>> x["machines"].remove("baz")
>>> x
{'username': 'admin', 'machines': ['foo', 'bar']}
>>> y
{'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
>>> y["machines"].remove("foo")
>>> y
{'username': 'admin', 'machines': ['bar', 'baz']}
>>> x
{'username': 'admin', 'machines': ['foo', 'bar']}
>>> x ={'username' : 'admin', 'machines' : ['foo', 'bar', 'baz']}
>>> y ={}
>>> y.fromkeys(x, "unknow")
{'username': 'unknow', 'machines': 'unknow'}
>>> y
{}
>>> y = y.fromkeys(x, "unknow")
>>> y
{'username': 'unknow', 'machines': 'unknow'}
>>> y = y.fromkeys(x)
>>> y
{'username': None, 'machines': None}
>>> z = {}
>>> z = z.fromkeys(range(10), "test")
>>> z
{0: 'test', 1: 'test', 2: 'test', 3: 'test', 4: 'test', 5: 'test', 6: 'test', 7: 'test', 8: 'test', 9: 'test'}
# 实测赋值只能是一个值!所有key的值都相同。
这个设计感觉很怪,你说y.fromkeys(x)生成的dict不会给y,是不是很怪?
>>> x ={'username' : 'admin', 'machines' : ['foo', 'bar', 'baz']}
>>> x.get("machines")
['foo', 'bar', 'baz']
>>> x.get("test")
>>> x.get("test", "this is a test")
'this is a test'
>>> x = {'username' : 'admin', 'machines' : ['foo', 'bar', 'baz'], "hello": "world"}
>>> x.items()
[('username', 'admin'), ('hello', 'world'), ('machines', ['foo', 'bar', 'baz'])]
>>> x.iteritems()
>>> list(x.iteritems())
[('username', 'admin'), ('hello', 'world'), ('machines', ['foo', 'bar', 'baz'])]
| iterkeys(...)
# 返回keys的迭代器
>>> x
{'username': 'admin', 'test': 'this is a test', 'hello': 'world', 'machines': ['foo', 'bar', 'baz']}
>>> x.update({"test": "changed"})
>>> x
{'username': 'admin', 'test': 'changed', 'hello': 'world', 'machines': ['foo', 'bar', 'baz']}
| values(...)
# 以list的形式返回所有value,list意味着可以返回重复的value
>>> x.viewkeys()
dict_keys(['username', 'test', 'hello', 'machines'])
>>> x.viewvalues()
dict_values(['admin', 'changed', 'world', ['foo', 'bar', 'baz']])
>>> d.viewitems()
dict_items([(1, 'gg'), (2, 'b'), (3, 'c'), (4, {1: 'a', 2: 'b', 3: 'mm'})])
|
【2014.4.9修订:内置sorted对keys()排序!】
和list比较,dict有以下几个特点:
而list相反:
dict是用空间来换取时间的一种方法。
>>> d = {1: "a", 2: "b", 3: "c"}
>>> d
{1: 'a', 2: 'b', 3: 'c'}
>>> dict((v, k) for k, v in d.iteritems())
{'a': 1, 'c': 3, 'b': 2}
>>> dict(zip(d.itervalues(), d.iterkeys()))
{'a': 1, 'c': 3, 'b': 2}
本文由@The_Third_Wave原创。不定期更新,有错误请指正。
Sina微博关注:@The_Third_Wave
如果这篇博文对您有帮助,为了好的网络环境,不建议转载,建议收藏!如果您一定要转载,请带上后缀和本文地址。