Leetcode之python使用记录

马肤
这是懒羊羊

 开始刷题,发现很久很久很久不写java以后,所有语法基本忘光了。决定用python开始刷题。

x = range(3, 6)
for n in x:
  print(n)
# 3, 4, 5
# 列表便利
s = [1,2,3]
for i in enumerate(s):
    print i
# (0,1)
# (1,2)
# (2,3)
# 如何修改列表
# nums =  doesn't replace elements in the original list.
# nums[:] = replaces element in place
# 查找列表元素的位置
list1.index('A')
# 删除列表元素
# 按照索引位置删除
list = [0,1,2,3]
list.pop(1)
# list [0,2,3]
# 按照值删除,删除首个符合值的元素
list = [0,1,2,3,1]
list.remove(1)
# list [0,2,3,1]
# 按照索引位置删除
list = [0,1,2,3,1]
del list[2]
# list [0,1,3,1]
del list[2:4] #从第二个开始到第四个为止,不包括第四个
# list [0,1,1]
del list
# 直接删除整个list
# python除法
 “/”,这是传统的除法,3/2=1.5
 “//”,在python中,这个叫“地板除”,3//2=1
 “%”,这个是取模操作,也就是区余数,4%2=0,5%2=1
# 计数函数
c = Counter('abcasdf')
#  Counter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})
for i, j in c.items():
    print(i,j)
c = Counter('abracadabra').most_common(3) #n不填返回全部
# [('a', 5), ('r', 2), ('b', 2)]
for i,j in c:
    print(i,j)
# 排序
l.sort(reverse=True) #从大到小排序
#map排序
#按照key排序
#按照value排序
d_sorted = sorted(d.items(), key=lambda item:item[1], reverse=True)
num = 10
if (num % 2) == 0:
   print("{0} 是偶数".format(num))
else:
   print("{0} 是奇数".format(num))
percent_01 = '%.4f%%' % (float(3) / float(40000) * 100)
print '------ percent_01 = ', percent_01
# 保留3位小数
percent_02 = '{:.3%}'.format(float(10) / float(100))
print '====== percent_02 = ', percent_02
#向下取整
>>> a = 3.75
>>> int(a)
3
math.floor(-0.3)
>>> -1
math.floor(0.9)
>>> 0
int(-0.5)
>>> 0
int(-0.9)
>>> 0
int(0.5)
>>> 0
int(0.9)
>>> 0
(-1) // 2  # -0.5
>>> -1
(-3) // 2  # -1.5
>>> -2
1 // 2    # 0.5 
>>> 0
3 // 2    # 1.5
>>> 1
#四舍五入
>>> round(3.25); round(4.85)
3.0
5.0
#向上取整
>>> import math
>>> math.ceil(3.25)
4.0
>>> math.ceil(3.75)
4.0
>>> math.ceil(4.85)
5.0
math.ceil(-0.5)
>>> 0
math.ceil(-0.9)
>>> 0
math.ceil(0.3)
>>> 1
>>> import math
>>> math.modf(3.25)
(0.25, 3.0)
>>> math.modf(3.75)
(0.75, 3.0)
>>> math.modf(4.2)
(0.20000000000000018, 4.0)
str1 = "12345"
list1 = list(str1)
print list1
# ['1', '2', '3', '4', '5']
# 在列表开头添加元素
>>> b = [1,2,3,4,5]
>>> b.insert(0,'x')
>>> b
['x', 1, 2, 3, 4, 5]

(图片来源网络,侵删)

文章版权声明:除非注明,否则均为VPS857原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复:表情:
评论列表 (暂无评论,0人围观)

还没有评论,来说两句吧...

目录[+]

取消
微信二维码
微信二维码
支付宝二维码