万字干货,Python语法大合集,一篇文章带你入门( 三 )

变量Python中声明对象不需要带上类型,直接赋值即可,Python会自动关联类型,如果我们使用之前没有声明过的变量则会出发NameError异常 。
# There are no declarations, only assignments.# Convention is to use lower_case_with_underscoressome_var = 5some_var# => 5# Accessing a previously unassigned variable is an exception.# See Control Flow to learn more about exception handling.some_unknown_var# Raises a NameError复制代码Python支持三元表达式,但是语法和C++不同,使用if else结构,写成:
# if can be used as an expression# Equivalent of C's '?:' ternary operator"yahoo!" if 3 > 2 else 2# => "yahoo!"复制代码上段代码等价于:
if 3 > 2:return 'yahoo'else:return 2复制代码listPython中用[]表示空的list,我们也可以直接在其中填充元素进行初始化:
# Lists store sequencesli = []# You can start with a prefilled listother_li = [4, 5, 6]复制代码使用Append和pop可以在list的末尾插入或者删除元素:
# Add stuff to the end of a list with appendli.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 popli.pop()# => 3 and li is now [1, 2, 4]# Let's put it backli.append(3)# li is now [1, 2, 4, 3] again.复制代码list可以通过[]加上下标访问指定位置的元素,如果是负数,则表示倒序访问 。-1表示最后一个元素,-2表示倒数第二个,以此类推 。如果访问的元素超过数组长度,则会出发IndexError的错误 。
# Access a list like you would any arrayli[0]# => 1# Look at the last elementli[-1]# => 3# Looking out of bounds is an IndexErrorli[4]# Raises an IndexError复制代码list支持切片操作,所谓的切片则是从原list当中拷贝出指定的一段 。我们用start: end的格式来获取切片,注意,这是一个左闭右开区间 。如果留空表示全部获取,我们也可以额外再加入一个参数表示步长,比如[1:5:2]表示从1号位置开始,步长为2获取元素 。得到的结果为[1, 3] 。如果步长设置成-1则代表反向遍历 。
# 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]# Return list from index 1 to 3 => [2, 4]li[2:]# Return list starting from index 2 => [4, 3]li[:3]# Return list from beginning until index 3=> [1, 2, 4]li[::2]# Return list selecting every second entry => [1, 4]li[::-1]# Return list in reverse order => [3, 4, 2, 1]# Use any combination of these to make advanced slices# li[start:end:step]复制代码如果我们要指定一段区间倒序,则前面的start和end也需要反过来,例如我想要获取[3: 6]区间的倒序,应该写成[6:3:-1] 。
只写一个:,表示全部拷贝,如果用is判断拷贝前后的list会得到False 。可以使用del删除指定位置的元素,或者可以使用remove方法 。
# Make a one layer deep copy using slicesli2 = li[:]# => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.# Remove arbitrary elements from a list with "del"del li[2]# li is now [1, 2, 3]# Remove first occurrence of a valueli.remove(2)# li is now [1, 3]li.remove(2)# Raises a ValueError as 2 is not in the list复制代码insert方法可以指定位置插入元素,index方法可以查询某个元素第一次出现的下标 。
# Insert an element at a specific indexli.insert(1, 2)# li is now [1, 2, 3] again# Get the index of the first item found matching the argumentli.index(2)# => 1li.index(4)# Raises a ValueError as 4 is not in the list复制代码list可以进行加法运算,两个list相加表示list当中的元素合并 。等价于使用extend方法:
# You can add lists# Note: values for li and for other_li are not modified.li + other_li# => [1, 2, 3, 4, 5, 6]# Concatenate lists with "extend()"li.extend(other_li)# Now li is [1, 2, 3, 4, 5, 6]复制代码我们想要判断元素是否在list中出现,可以使用in关键字,通过使用len计算list的长度:
# Check for existence in a list with "in1 in li# => True# Examine the length with "len()"len(li)# => 6tupletuple和list非常接近,tuple通过()初始化 。和list不同,tuple是不可变对象 。也就是说tuple一旦生成不可以改变 。如果我们修改tuple,会引发TypeError异常 。
# Tuples are like lists but are immutable.tup = (1, 2, 3)tup[0]# => 1tup[0] = 3# Raises a TypeError复制代码由于小括号是有改变优先级的含义,所以我们定义单个元素的tuple,末尾必须加上逗号,否则会被当成是单个元素:


推荐阅读