1. Sequential Data Types
Unlike other programming languages Python uses the same syntax and function names to work on sequential data types.
- Bytes
- 0 ~ 255 --> 对应ASCII
- Lists
- Mutable
- Arbitrary objects
- Variable Size
[42, "What's the question?", 3.1415]
- Tuples
- Immutable list
- Faster than list
- Can be used as keys in dictionaries
t = ("tuples", "are", "immutable")
- Slicing
- s[begin: end]
- s[begin: end: step]
s[begin], s[begin + 1 * step], ... s[begin + i * step] for all (begin + i * step) < end.
str[0:6]
str[5:]
without_last_five = str[0:-5]
str[:]
str[::3]
- Operations
- contain
"a" not in abc
"x" in str
- repetition
3 * ["a","b","c"]
pitfall: repetition operator "*4" creates 4 references to the list x
>>> x = ["a","b","c"]
>>> y = [x] * 4
>>> y
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
>>> y[0][0] = "p"
>>> y
[['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c']]
>>>
2. Lists
A list can be seen as a stack.
- append
- Return "None"
lst = [3, 5, 7]
lst.append(42) // list == [3, 5, 7, 42]
lst = lst.append(42) // list == None
- pop(i)
- Return and remove 第i个 element
- Without an argument. The last element will be returned.
cities = ["Hamburg", "Linz", "Salzburg", "Vienna"]
cities.pop(0) // cities == ['Linz', 'Salzburg', 'Vienna']
cities.pop() // cities.pop(-1)
- extend
- appending all the elements of an iterable(e.g. list, tuple, string)
lst = ["a", "b", "c"]
programming_language = "Python"
lst.extend(programming_language) // ['a', 'b', 'c', 'P', 'y', 't', 'h', 'o', 'n']
- '+'
- 注意:不要用
x = x + [...]
L = [3, 4]
// L 为新的对象,具有新的id!千万不要这么用!
L = L + [42]
// 在原对象的基础上添加,id没变
L += [42]
L.append(42)
L.extend([42])
- remove
- remove the first occurrence of an element
- If not contained, a ValueError will be raised.
colours = ["red", "green", "blue", "green", "yellow"]
colours.remove("green")
index
s.index(x[, start, end])
insert
s.insert(index, object)
3. Shallow and Deep Copy
- Shallow Copy
- Copy Reference
colours1 = ["red", "blue"]
colours2 = colours1
colours2[1] = "green" // side effect: 两个list都会为['red', 'green']
-
Copy with Slice Operator
- 对于shallow list(无sublist的list),无side effect
list1 = ['a','b','c','d']
list2 = list1[:]
list2[1] = 'x' // list1 没有变
* 对于非shallow list,有side effect
lst1 = ['a','b',['ab','ba']]
lst2 = lst1[:]
lst2[0] = 'c' //lst1不变
lst2[2][1] = 'd' //lst1改变
* Deep Copy
* 所有元素(包括sublist),都被copy为新的对象
lst2 = deepcopy(lst1)
###4. Dictionaries
> Can use arbitrary types as values in a dictionary, but only immutable data types can be used as keys
dic = { (1,2,3):"abc", 3.1415:"abc"}
1. Operators
* pop(k) ---> remove (k, v) and return v
* pop(k, d) ---> if k not contains, return default value d
* popitem() ---> 无参数,随机remove
* get(k) ---> if k not contains, return None
* get(k, d) ---> if k not contains, return default value d
* copy() ---> shallow copy
* update() --->用于merge两个dict
knowledge = {"Frank": {"Perl"}, "Monica":{"C","C++"}}
knowledge2 = {"Guido":{"Python"}, "Frank":{"Perl", "Python"}}
knowledge.update(knowledge2) // {'Frank': {'Python', 'Perl'}, 'Guido': {'Python'}, 'Monica': {'C', 'C++'}}
* keys() & values() ---> 遍历
2. List <=> Dict
* Dict -> List
* (K, V) 被转成tuple
w = {"house":"Haus", "cat":"", "red":"rot"}
items_view = w.items()
items = list(items_view) //[('house', 'Haus'), ('cat', ''), ('red', 'rot')]
keys_view = w.keys()
keys = list(keys_view) //['house', 'cat', 'red']
values_view = w.values()
values = list(values_view) //['Haus', '', 'rot']
* List -> Dict
dishes = ["pizza", "sauerkraut", "paella", "hamburger"]
countries = ["Italy", "Germany", "Spain", "USA"]
//方法1
country_specialities = list(zip(countries, dishes)) //按位置匹配
country_specialities_dict = dict(country_specialities) //list转换dict
//方法2
country_specialities_zip = zip(dishes,countries) //返回iter
country_specialities_dict = dict(country_specialities_zip) //直接用iter生成dict
> 注意:zip()返回的是iterator,再第一次遍历完之后会自己销毁,不能再第二次使用
###5. Set
1. doesn't allow mutable objects
x = set(["Perl", "Python", "Java"])
adjectives = {"cheap","expensive","inexpensive","economical"}
* sets are mutable
* Frozensets are immutable
cities = frozenset(["Frankfurt", "Basel","Freiburg"])
4. Operations
colours.add("yellow")
cities.clear()
cities_backup = more_cities.copy() // shallow copy
x.difference(y).difference(z)
x - y - z // same as above
x.difference_update(y)
x = x - y // same as above
x.discard("a") //not contains, nothing happen
x.remove("a") //not contains, KeyError
x.intersection(y)
x & y //same as above
x.isdisjoint(y)
x.issubset(y)
x < y //same as above
x.issuperset(y)
x > y //same as above
x.pop() //removes and returns an arbitrary set element