原网页 https://learnxinyminutes.com/docs/python3/
###################################################### 2. Variables and Collections####################################################
# 打印
print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
# 默认打印会在打印的最后换行
# Use the optional argument end to change the end string.
print("Hello, World", end="!") # => Hello, World!
# 控制台输入数据
input_string_var = input("Enter some data: ")
# 以string类型返回数据
# Note: 早期版本的PY 这个方法叫raw_input()
# 不用声明
# Convention is to use lower_case_with_underscores
some_var = 5
some_var # => 5
# 使用一个未初始化的变量可能导致异常
# See Control Flow to learn more about exception handling.
some_unknown_var # Raises a NameError
# if can be used as an expression
# Equivalent of C's '?:' ternary operator
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
# 数组
li = []
# You can start with a prefilled list
other_li = [4, 5, 6]
# Add stuff to the end of a list with append 增加数组
li.append(1) # li is now [1]
li.append(2) # li is now [1, 2]
li.append(4) # li is now [1, 2, 4]
li.append(3) # li is now [1, 2, 4, 3]
# Remove from the end with pop 使用pop移除结尾元素
li.pop(3) # => 3 and li is now [1, 2, 4]
# Let's put it back
li.append(3) # li is now [1, 2, 4, 3] again.
# Access a list like you would any array 访问链表
li[0] # => 1 头
# Look at the last element 尾
li[-1] # => 3
# Looking out of bounds is an IndexError大于边界会引起错误
li[4] # Raises an IndexError
# You can look at ranges with slice syntax.
# The start index is included, the end index is not
# (It's a closed/open range for you mathy types.)
li[1:3] # => [2, 4]
# Omit the end 省略尾
li[2:] # => [4, 3] 第2个元素之后
# Omit the beginning 第3个元素之前
li[:3] # => [1, 2, 4]
# Select every second entry
li[::2] # =>[1, 4]
#??抱歉,这个没太看懂
# Return a reversed copy of the list
li[::-1] # => [3, 4, 2, 1] 倒序
# Use any combination of these to make advanced slices
# li[start:end:step]
# Make a one layer deep copy using slices利用切片进行拷贝
li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. 此时li2 is li1 会导致错误
# Remove arbitrary elements from a list with "del"
使用del删除元素
del li[2] # li is now [1, 2, 3]
# Remove first occurrence of a value移除第一次出现的某个值
li.remove(2) # li is now [1, 3]
li.remove(2) # Raises a ValueError as 2 is not in the list
如果此时队列中没有2,则会报错
# Insert an element at a specific index 在指定位置插入元素
li.insert(1, 2) # li is now [1, 2, 3] again 在第1+1位插入元素2
# Get the index of the first item found matching the argument 根据值找到它在数组中第一次出现的位置
li.index(2) # => 1
li.index(4) # Raises a ValueError as 4 is not in the list 当4不在数组中时便会报错
# You can add lists
# Note: values for li and for other_li are not modified.
#你可以通过下述方法相加链表,此时li与o_li中的值并未改变
li + other_li # => [1, 2, 3, 4, 5, 6]
# Concatenate lists with "extend()"使用extend连接两个表
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
# Check for existence in a list with "in"
#使用in判断一个值在不在表内
1 in li # => True
# Examine the length with "len()" 使用len得到一个表的长度
len(li) # => 6
(刚刚仔细想了一下,感觉上面list应该叫可变序列)
# Tuples are like lists but are immutable. 元组,不可变的序列
tup = (1, 2, 3)
tup[0] # => 1
tup[0] = 3 # Raises a TypeError 不能对其中的值进行改变
# Note that a tuple of length one has to have a comma after the last element but
# tuples of other lengths, even zero, do not.
注意只有一个元素的元组在元素后应该保留一个逗号,其他任意长度包括0都不需要
type((1)) # => <class 'int'>
type((1,)) # => <class 'tuple'>
type(()) # => <class 'tuple'>
# You can do most of the list operations on tuples too
大部分对可变序列的操作对元组同样有效
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => True
# You can unpack tuples (or lists) into variables
你可以把元组拆成一个个变量
a, b, c = (1, 2, 3)
# a is now 1, b is now 2 and c is now 3# You can also do extended unpacking
a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4
# Tuples are created by default if you leave out the parentheses
像下面一样,如果你没有加括号的话,会自动建立成元组
d, e, f = 4, 5, 6
# Now look how easy it is to swap two values
这下你会发现交换两个值是如何简单
e, d = d, e
# d is now 5 and e is now 4
# Dictionaries store mappings from keys to values
字典可以把关键词与值对应起来
empty_dict = {} #空字典
# Here is a prefilled dictionary 初始化后的字典
filled_dict = {"one": 1, "two": 2, "three": 3}
# Note keys for dictionaries have to be immutable types. This is to ensure that# the key can be converted to a constant hash value for quick look-ups.
注意字典中的关键词必须是不变的类型,这是为了确保关键词能够被转换成连续的哈希值,从而迅速查找。
(哈希值最近学习图像检索有所接触)
# Immutable types include ints, floats, strings, tuples.
这些类型包括 整型,浮点型,字符串,元组
invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' 可变序列是无法被哈希的类型,从而会报错
valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type,
#而字典中的值可以为任何类型
however.
# Look up values with []
filled_dict["one"] # => 1
# Get all keys as an iterable(迭代) with "keys()". We need to wrap the call in list()# to turn it into a list. We'll talk about those later.
Note - Dictionary key# ordering is not guaranteed. Your results might not match this exactly.
注意字典中的关键词的顺序并不能保证,你可能得到的结果并不能和你所预期的精确匹配。
list(filled_dict.keys()) # => ["three", "two", "one"]
# Get all values as an iterable with "values()".
使用values()方法得到所有的值
Once again we need to wrap it# in list() to get it out of the iterable.
我们需要把它包裹进list()中
Note - Same as above regarding key# ordering.list(filled_dict.values()) # => [3, 2, 1]
# Check for existence of keys in a dictionary with "in"
使用in来检查关键词是否在字典中
"one" in filled_dict # => True
1 in filled_dict # => False
# Looking up a non-existing key is a KeyError
filled_dict["four"] # KeyError
# Use "get()" method to avoid the KeyError
使用get方法来避免关键词错误
filled_dict.get("one") # => 1
filled_dict.get("four") # => None
# The get method supports a default argument when the value is missing
当没有实值时,get方法返回缺省值
filled_dict.get("one", 4) # => 1
filled_dict.get("four", 4) # => 4
# "setdefault()" inserts into a dictionary only if the given key isn't present
使用setdefault方法插入关键词 当关键词不存在在字典中时
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
# Adding to a dictionary
filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
filled_dict["four"] = 4 # another way to add to dict
# Remove keys from a dictionary with del
del filled_dict["one"] # Removes the key "one" from filled dict
# From Python 3.5 you can also use the additional unpacking options
{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
{'a': 1, **{'a': 2}} # => {'a': 2}
# Sets store ... well sets
empty_set = set()# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
# Similar to keys of a dictionary, elements of a set have to be immutable.
invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}
# Add one more item to the set
filled_set = some_setfilled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
# Do set intersection with & 交
other_set = {3, 4, 5, 6}
filled_set & other_set # => {3, 4, 5}
# Do set union with | 并
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Do set difference with -
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
# Do set symmetric difference with ^ 对称差
{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
# Check if set on the left is a superset of set on the right子集
{1, 2} >= {1, 2, 3} # => False
# Check if set on the left is a subset of set on the right{1, 2} <= {1, 2, 3} # => True
# Check for existence in a set with in
2 in filled_set # => True
10 in filled_set # => False
初步学习,记录自己的学习进度,可能有点理解不准确,请见谅,欢迎提出问题