python易错知识集合

本篇用于记录在写leetcode时遇到的python易错知识。

2019.8.29

1.Python range() 函数用法:

range(start, stop[, step])
  • start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
  • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
  • step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

2.python数组删除元素的三种方法:

1)remove: 删除单个元素,删除首个符合条件的元素,按值删除

举例说明:
>>> str=[1,2,3,4,5,2,6]
>>> str.remove(2)
>>> str
[1, 3, 4, 5, 2, 6]

2)pop:  删除单个或多个元素,按位删除(根据索引删除)
>>> str=[0,1,2,3,4,5,6]
>>> str.pop(1)   #pop删除时会返回被删除的元素
>>> str
[0, 2, 3, 4, 5, 6]

3)del:它是根据索引(元素所在位置)来删除
举例说明:
>>> str=[1,2,3,4,5,2,6]
>>> del str[1]
>>> str
[1, 3, 4, 5, 2, 6]

del还可以删除指定范围内的值。
>>> str=[0,1,2,3,4,5,6]
>>> del str[2:4]  #删除从第2个元素开始,到第4个为止的元素(但是不包括尾部元素)
>>> str
[0, 1, 4, 5, 6]

注意:del是删除引用(变量)而不是删除对象(数据),对象由自动垃圾回收机制(GC)删除。

2019.8.30

1.python自带库:collections

collections是Python内建的一个集合模块,提供了许多有用的集合类。

Counter是collections库的函数,是一个简单的计数器,例如,统计字符出现的个数:

from collections import Counter
c = Counter()
for ch in 'programming':
    c[ch] = c[ch] + 1
print(c)
>>Counter({'r': 2, 'g': 2, 'm': 2, 'p': 1, 'o': 1, 'a': 1, 'i': 1, 'n': 1})

2019.9.3

1.数组添加元素

1)append

在数组末尾添加元素

list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("更新后的列表 : ", list1)
更新后的列表 :  ['Google', 'Runoob', 'Taobao', 'Baidu']

2)insert

在数组指定位置插入元素

list.insert(index, obj)
index -- 对象 obj 需要插入的索引位置。
obj -- 要插入列表中的对象。

aList = [123, 'xyz', 'zara', 'abc']
aList.insert( 3, 2009)
print "Final List : ", aList

Final List : [123, 'xyz', 'zara', 2009, 'abc']

 2019.9.9

1.字典的get():

字典的get()方法可用于解决字典对字典里键值的增加。

dict.get(key, default=None)
key -- 字典中要查找的键。
default -- 如果指定键的值不存在时,返回该默认值值。

dict1 = {}
dict1[0]=4
print(dict1)
>>{0: 4}
dict1[0] = dict1.get(0,0)+1
print(dict1)
>>{0: 5}

get()方法搜索0,若0不存在,则把0的值设为0;若0存在,则把0的值+1。

2019.9.9

1.列表转字符串:

res = [2,5,7,9]
result = "".join(str(i) for i in res)
print(result)
print(type(result))
>>2579
>><class 'str'>

 2019.9.14

1.python文件读写

python 文件读写可用 open 和with open 两种方式。

# opem
try
: f = open('/path/to/file', 'r') print(f.read()) finally: if f: f.close()
# with open
with open("..\test.txt", 'w') as f:
    f.write("hello")
    f.read()

with open 方法,无需close,每次进行操作完便会自动关闭。

# 文件读写方式
r : 只读
r+ : 读写 从头开些
w: 只写
w+: 读写 从头开写
a: 写 继续写入
a+: 读写 继续写入
# IO 常用method tell():告诉你文件内的当前位置 必须先导入OS模块 rename():修改文件名 os.rename(current_file_name, new_file_name) remove():删除文件名 os.remove(file_name) mkdir():创建目录 os.mkdir("newdir") chdir():改变当前目录 os.chdir("newdir")

 

posted @ 2019-08-29 10:05  耳东三羊  阅读(443)  评论(0编辑  收藏  举报