python的dictionary类型和JSON类似,
定义dict类型的方法: 使用{}构造符或dict()
>>> new_dict={}
>>> type(new_dict)
<class 'dict'>
>>> new_dict2=dict()
>>> type(new_dict2)
<class 'dict'>
如下 :
>>> new_dict1={"a":"hello", "b":[1,2,3,4,5]}
>>> print(new_dict1)
{'a': 'hello', 'b': [1, 2, 3, 4, 5]}
甚至还可以嵌套
>>> new_dict3={"hello":new_dict2,"a":"b"}
>>> print(new_dict3)
{'hello': {}, 'a': 'b'}
>>> new_dict2=new_dict3
>>> print(new_dict3)
{'hello': {}, 'a': 'b'}
>>> new_dict2={"www":"sky-mobi"}
>>> print(new_dict3)
{'hello': {}, 'a': 'b'}
[其他]
list的用法举例, pop用于取出最后一个值, FILO的方式取数据.
>>> new_l1=[1,2,3,4,5,6]
>>> new_l1.pop()
6
>>> new_l1.pop()
5
>>> new_l1.pop()
4
>>> new_l1
[1, 2, 3]
扩展单个元素使用append
>>> new_l1.append(4)
>>> new_l1.pop()
4
扩展多个元素使用extend
>>> new_l1.extend([4,5,6,7])
>>> new_l1.pop()
7
>>> new_l1
[1, 2, 3, 4, 5, 6]
按位置插入使用insert
>>> new_l1.insert(1,10)
>>> new_l1
[1, 10, 2, 3, 4, 5, 6]
直接倒序, 使用reverse
>>> new_l1.reverse()
>>> new_l1
[6, 5, 4, 3, 2, 10, 1]
按index位置取数据
>>> new_l1.pop(1)
5
清除使用remove(x)或clear()
Operation | Result | Notes |
---|---|---|
s[i] = x | item i of s is replaced by x | |
s[i:j] = t | slice of s from i to j is replaced by the contents of the iterable t | |
del s[i:j] | same as s[i:j] = [] | |
s[i:j:k] = t | the elements of s[i:j:k] are replaced by those of t | (1) |
del s[i:j:k] | removes the elements of s[i:j:k] from the list | |
s.append(x) | appends x to the end of the sequence (same ass[len(s):len(s)] = [x]) | |
s.clear() | removes all items from s (same as del s[:]) | (5) |
s.copy() | creates a shallow copy of s (same as s[:]) | (5) |
s.extend(t) | extends s with the contents of t (same ass[len(s):len(s)] = t) | |
s.insert(i, x) | inserts x into s at the index given by i (same as s[i:i] =[x]) | |
s.pop([i]) | retrieves the item at i and also removes it from s | (2) |
s.remove(x) | remove the first item from s where s[i] == x | (3) |
s.reverse() | reverses the items of s in place | (4) |
Notes:
-
t must have the same length as the slice it is replacing.
-
The optional argument i defaults to -1, so that by default the last item is removed and returned.
-
remove raises ValueError when x is not found in s.
-
The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence.
-
clear() and copy() are included for consistency with the interfaces of mutable containers that don’t support slicing operations (such as dict andset)
New in version 3.3: clear() and copy() methods.