p.s. 最近在做NLP的任务,用熟悉的C++做发现C++有很多不方便的地方,尤其是中文编码的转化,非常繁琐。故采用Python。本文主要就基本数据结构、控制流等几个基本语法方面,给出总结。
参考资料:《Python编程:从入门到实践》
目录
print——基本输出
-
类似C中的printf,但会在末尾自动换行
print("hello world!")
- 也可直接输出字符串变量的值
message = "hello world!"
print(message);
-
C++中的转移字符在此处同样适用
input()——基本输入(字符串)
可直接在函数内部输入提示用户输入的提示字符串
mess = input("please input something:")
print(mess)
当要将字符串转换成数值时可用int()
字符串和数值的相互转换
- 字符串 --> 数值: int()
- 数值 --> 字符串:str()
if——条件语句
a = 10
if a < 4:
print("1")
elif a > 4 and a < 10:
print("2")
else:
print("3")
- 与或非:and, or, not
- 判断列表非空
a = [1,2,3,4] if a: print("a not empty!")
while——循环语句
i = 1
while i <= 10:
print(i)
i += 1
注释
- 使用“#”
字符串
- 整形、浮点型等其他数据类型 --> 字符串:str()
a = 23 stri = "this a test:" + str(a) print(stri)
列表——类似C中的数组
- 数据类型表示[a,b,..,z]
a = ['hello','world','!!']
- 访问某个列表元素"[ ]"(和C一样,列表的第一个元素从0开始)。
a = ['hello','world','!!']
print(a[1])
这里有个有意思的地方,Python支持访问下标为负数,表示列表元素的倒数第N个
a = ['hello','world','!!']
print(a[-1]) #访问最后一个元素
- 添加元素
末尾添加: append()
a = ['hello','world','!!']
print(a[-1]) #访问最后一个元素
a.append('~~')
print(a[-1])
任意位置插入:insert()
a = ['hello','world','!!']
print(a[-1]) #访问最后一个元素
a.insert(0,'~')
print(a[0])
- 删除元素
del
def a[0]
pop():删除末尾元素
a.pop()
pop(n):等于del
a.pop(1)
remove():根据列表的值删除元素 (返回删除元素的值)
a = [1,2,3]
a.remove(2)
- 排序
临时排序sorted()
永久排序sort()
列表反转reverse()
- 求长度:len()
- 列表遍历(类似C++里的范围for循环)
strs = ['hello','world','!!'] for s in strs: print(s)
每条循环,会打印出一个换行
注意缩进!!!注意for结尾的冒号(告诉编译器下一行是for循环的开始)!!!
可以只对一部分列表进行遍历:注意[a,b]包括第a个元素,不包括第b个元素strs = ['hello','world','!!'] for s in strs[1:]: print(s) #--------------------------------------------------------# strs = ['hello','world','!!'] for s in strs[:1]: print(s) #--------------------------------------------------------# strs = ['hello','world','!!'] for s in strs[:-1]: print(s) #--------------------------------------------------------#
-
列表复制
strs = ['hello','world','!!'] strs_ = strs[:]
当然,也可以只复制一部分,范围[]的使用和for遍历中一样。
- 判断某个值是否包含在列表里:in
字典
字典是Python中一个强大的数据结构<key,value>,个人理解类似于c++中的pair。学习时要特别注意字典和列表的组合情况。
不同于列表,字典不关系元素间的顺序
- 基本使用例子
dictor = {'key':'a', 'index': 1} print(dictor) print(dictor['key']) print(dictor['index'])
- 添加字典的值
dictor = {'key':'a', 'index': 1} print(dictor) dictor['string'] = "this a string~" print(dictor)
- 修改字典的值
dictor = {'key':'a', 'index': 1} print(dictor) dictor['key'] = 'b' print(dictor)
- 删除字典的值
dictor = {'key':'a', 'index': 1} print(dictor) del dictor['key'] print(dictor)
- 遍历字典--<key,value>
dictor = {'key':'a', 'index': 1} print(dictor) for k,v in dictor.items(): print(k+","+str(v))
- 遍历字典--keys
dictor = {'key':'a', 'index': 1} print(dictor) for k in dictor.keys(): print(k)
- 遍历字典--values
dictor = {'key':'a', 'index': 1} print(dictor) for v in dictor.values(): print(v)