现充|junyu33

C转python速成

本教程只介绍将python作为一种脚本语言所需要的基本知识点。其目的不是为了机器学习或者数据分析,而是让你写出代码短小、易于维护,而且永远也不会爆ull脚本

具有良好C基础的读者可以在一个下午掌握这些知识点。

本教程部分引用了廖雪峰的博客,且以python3为基础。

与C的主要区别

I/O

with open('D:/tmp1/file.txt','a') as f:
   f.write('this is a trivial test for file I/O.')
with open('D:/tmp1/file.txt') as f:
   content = f.read()
print(content) #然而文件本身有中文时乱码了,「你好」变成了「浣犲ソ」,解决方法在后文。
f.close()

Data type & transfer

变量从创建(赋值)好后,它的类型便确定了。可以通过type(var)来查看其类型。

'''hello,
world!''' #字符串可以换行书写

Encoding

(我终于能处理带中文字符的文件了!)

字符 ASCII Unicode UTF-8
A 01000001 00000000 01000001 01000001
× 01001110 00101101 11100100 10111000 10101101
>>> b'ABC'.decode('ascii')
'ABC'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'中文'

回到之前的文件I/O,我们只需要在第二次打开文件时加上一项encoding = 'utf-8'即可。

Basic databases

在python,数据结构被作为对象来处理,它们本身已经内置了一些方法,这是与面向过程的C的一个重要不同点。

list——[]

tuple——()

tuple一旦创建,就不能修改

dict——{}

(dict类似于c++中的map。我本来以为dict也是靠rb-tree实现的,结果一个错误告诉我它是靠hash实现的,因此dict中的元素必须是str、tuple等不可变对象,而不能插入list)

set——set(list)

顾名思义,set中不会含有重复的元素。

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

Condition and loop

条件语句剩下的注意事项看以下例子:

age = int(input())
if age >= 6:
    print('teenager')
elif age >= 18:
    print('adult')
else:
    print('kid')
subjects = ['calculus', 'programming', 'politics']
for i in subjects:
    print(i)
sum = 0
for x in range(101):
    sum = sum + x
print(sum)
sum = 0
for x in range(101):
    if x > 50:
        break
    elif x & 1:
        continue
    sum = sum + x
print(sum)
>>> L = list(range(100))
>>> L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> L[:10:2]
[0, 2, 4, 6, 8]
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
>>> L[:]
[0, 1, 2, 3, ..., 99]
>>> L[::-1]
[99, 98, 97, 96, ..., 0]

Function

一个简单的阶乘函数:

def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)
def rot90(x, y):
    tmp = x
    x = -y
    y = tmp
    return x, y

位置参数

跟你C语言的参数是一个意思。

默认参数

比如之前open函数的帮助文档是这样写的:

>>> help(open)
Help on built-in function open in module io:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise OSError upon failure.

    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
-- More  --

注意:默认参数需要指向不可变对象!否则每一次函数运行后,得到的结果都可能不同。

Summary

The best way to learn a language is to use it.

快去刷题!