Python基础知识总结和示例

本文主要介绍python Numpy的一些用法和相关知识。本文的最主要特点是看代码学习,每个知识点都有相应的代码示例。

python

Python是一种高级,动态类型化的多范式语言。Python代码经常被说为几乎是伪代码,因为你可以用简单的而且可读性很搞的几行代码写出非常强大功能思想。下面一个用python写的经典的快速排序算法。

def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quicksort(left) + middle + quicksort(right)

print(quicksort([3,6,8,10,1,2,1]))

代码解析,可以看到该代码中没有任何循环的语句,直接用5句话就解决问题了,比较简洁,也容易读懂。

第1行定义了函数名;

第2,3行判断了传入的列表长度,用len可以求列表的长度。如果列表的长度不大于1,那么就不用比较,直接返回该列表,这也是递归结束的判断条件;

第4行,求取该列表中间位置的元素值。//是向下取整运算;

第5行,把所有小于中间值的元素筛选出来。这里用了非常简洁的写法。[]中的x是一个变量,这个变量是不用声明,直接使用。然后从列表arr中取数,x in arr 。if x < pivot是条件。这里面相当于有3句话。第一句定义一个变量x,第2句是从arr中取数。第3句是条件判断。即把满足条件的x筛选出来放在left中。

第6行,取出中间值。

第7行,把大于中间值的放在right中。

第8行,return返回quicksort函数,再次调用。然后再次循环以上过程,直到有列表的长度为1为止。

python 版本

截止到2020年1月1日,python官方不再支持python2。本教程中使用python3.6。在terminal中输入python --version可以查看python的版本。

基本数据类型

向其他语言一样,python有许多基础数据类型,包括整型(integer),浮点型(float),布尔型(boolean)和字符串(string)。这些数据类型和其它语言比较相似。

数值(Numbers)

x = 3
print(type(x)) # Prints "<class 'int'>"
print(x)       # Prints "3"
print(x + 1)   # Addition; prints "4"
print(x - 1)   # Subtraction; prints "2"
print(x * 2)   # Multiplication; prints "6"
print(x ** 2)  # Exponentiation; prints "9"
x += 1
print(x)  # Prints "4"
x *= 2
print(x)  # Prints "8"
y = 2.5
print(type(y)) # Prints "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"

以上代码比较简单,大家可以在自己的python console中输入一遍,看看结果。

需要注意的是,python与其它语言不同的是,python没有自加x++,和自减x--这种操作。

python还有其它供复数使用的内建函数,可以在https://docs.python.org/3.5/library/stdtypes.html#numeric-types-int-float-complex里找到所有它的详细用法。

布尔值(Boolean)

python支持所有常用的布尔运算,但是python使用英语单词而不是&&,||等这些符号。

t = True
f = False
print(type(t)) # Prints "<class 'bool'>"
print(t and f) # Logical AND; prints "False"
print(t or f)  # Logical OR; prints "True"
print(not t)   # Logical NOT; prints "False"
print(t != f)  # Logical XOR; prints "True"

字符串(string)

python比较支持字符串。

hello = 'hello'    # String literals can use single quotes
world = "world"    # or double quotes; it does not matter.
print(hello)       # Prints "hello"
print(len(hello))  # String length; prints "5"
hw = hello + ' ' + world  # String concatenation
print(hw)  # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting
print(hw12)  # prints "hello world 12"

注意第5行中使用了字符串的拼接,这个是字符串拼接常用的方法,只用列表的拼接也可以使用+。

第6行中使用另一种字符串拼接的方法,格式化拼接。

字符串还有一些其它有用的方法,比如:

s = "hello"
print(s.capitalize())  # Capitalize a string; prints "Hello"
print(s.upper())       # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7))      # Right-justify a string, padding with spaces; prints "  hello"
print(s.center(7))     # Center a string, padding with spaces; prints " hello "
print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another;
                                # prints "he(ell)(ell)o"
print('  world '.strip())  # Strip leading and trailing whitespace; prints "world"

容器(Container)

Python有一些内建容器,比如列表list,字典dictionary,集合set和元组tuple。

列表list

Python中的列表是数组的一种等效,但是列表的大小可以改变,并且可以装不同类型的元素。

xs = [3, 1, 2]    # Create a list
print(xs, xs[2])  # Prints "[3, 1, 2] 2"
print(xs[-1])     # Negative indices count from the end of the list; prints "2"
xs[2] = 'foo'     # Lists can contain elements of different types
print(xs)         # Prints "[3, 1, 'foo']"
xs.append('bar')  # Add a new element to the end of the list
print(xs)         # Prints "[3, 1, 'foo', 'bar']"
x = xs.pop()      # Remove and return the last element of the list
print(x, xs)      # Prints "bar [3, 1, 'foo']"

注意列表可以索引,添加append,弹出pop元素。想进一步学习列表的话,可以参见https://docs.python.org/3.5/tutorial/datastructures.html#more-on-lists

切片(slicing)

为了一次得到列表中的多个数据,Python提供了精确的语法得到列表的子列表。

nums = list(range(5))     # range is a built-in function that creates a list of integers
print(nums)               # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4])          # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])           # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])           # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])            # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[:-1])          # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9]        # Assign a new sublist to a slice
print(nums)               # Prints "[0, 1, 8, 9, 4]"

循环(loop)

我们可以用in循环列表中的元素。

animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print(animal)
# Prints "cat", "dog", "monkey", each on its own line.

如果我们想连同列表的索引一起打印出来,可以用enumerate函数。

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line

列表append的用法:

nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
    squares.append(x ** 2)
print(squares)   # Prints [0, 1, 4, 9, 16]

计算上述nums的平方,还有更加简洁的写法:

nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares)   # Prints [0, 1, 4, 9, 16]

在列表中还可以加判断条件,比如要计算num中偶数的平方。

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)  # Prints "[0, 4, 16]"

 

本文主要参考至:https://cs231n.github.io/python-numpy-tutorial/。有兴趣的可以直接看原文。本文会持续更新。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值