首页 > 编程语言 > 详细

[2020-06-21]python基础回顾

时间:2020-06-21 19:24:46      阅读:64      评论:0      收藏:0      [点我收藏+]

 

 

python常见函数

数学函数

pow(a, b) 求a的b次幂

abs(a) 求a的绝对值

round(a) 求距离a最近的整数

sqrt(a) 求开发

input(‘please input your number: ‘) 终端输入函数

raw_input(‘please input your number: ‘) 终端输入函数

max() 返回序列中最大值

min() 返回序列中最小值

len() 返回序列的长度

 

python序列 

索引

索引到第一个元素str[0]

>>> str

‘hi,today is Sunday!‘

>>> str[0]

‘h‘

索引到最后一个元素str[-1]

>>> str[-1]

‘!‘

索引到倒数第二个元素str[-2]

>>> str[-2]

‘y‘

 

分片

list[2,4]表示取出2<=index<4之间的元素

>>> list=[‘a‘,‘b‘,‘c‘,‘1‘,‘2‘,‘3‘]

>>> list[2:4]

[‘c‘, ‘1‘]

 

步长

默认步长值为1,可以在第三个参数中指定numbers[0:9:2]步长为2

>>> numbers

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> numbers[0:9:1]

[0, 1, 2, 3, 4, 5, 6, 7, 8]

>>> numbers[0:9:2]

[0, 2, 4, 6, 8]

>>> numbers[0:9:4]

 

序列相加

和序列相乘一样,得到了拼接效果

>>> list_1=[0,2,4]

>>> list_2=[1,3,5]

>>> list_1 + list_2

[0, 2, 4, 1, 3, 5]

 

序列相乘

和序列相加一样,得到了拼接效果

>>> list_1

[0, 2, 4]

>>> list_1 * 3

[0, 2, 4, 0, 2, 4, 0, 2, 4]

 

删除元素

>>> numbers

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> del numbers[0]

>>> numbers

[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> 

>>> del numbers[0:3]

>>> numbers

[4, 5, 6, 7, 8, 9]

 

列表的方法

count

统计list中某个元素出现的个数 

>>> n=[‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘]

>>> n

[‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘]

>>> n.count(‘a‘)

1

>>> n.count(‘ac‘)

1

 

append 

在list末尾追加元素

>>> n

[‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘]

>>> n.append(‘end‘)

>>> n

[‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘, ‘end‘]

 

extend

在末尾追加另一个列表的多个元素 

>>> n

[‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘, ‘end‘]

>>> 

>>> n1 = [‘extra‘]

>>> n.extend(n1)

>>> n

[‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘, ‘end‘, ‘extra‘]

 

insert 

在列表中插入元素,insert(i, node)表示在索引为i的位置,插入元素node

>>> n

[‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘, ‘end‘, ‘extra‘]

>>> n.insert(0, ‘first‘)

>>> n

[‘first‘, ‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘, ‘end‘, ‘extra‘]

 

pop

移出最尾元素的值,此时列表发生变化

>>> n

[‘first‘, ‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘, ‘end‘, ‘extra‘]

>>> 

>>> n.pop()

‘extra‘

>>> n

[‘first‘, ‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘, ‘end‘]

 

remove

移除列表中某个元素

>>> n

[‘first‘, ‘a‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘, ‘end‘]

>>> n.remove(‘a‘)

>>> n

[‘first‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘, ‘end‘]

 

reverse

将列表中的元素按照索引顺序反向排列

>>> n

[‘first‘, ‘b‘, ‘c‘, ‘ac‘, ‘bc‘, ‘cd‘, ‘end‘]

>>> n.reverse()

>>> n

[‘end‘, ‘cd‘, ‘bc‘, ‘ac‘, ‘c‘, ‘b‘, ‘first‘]

 

sort

将列表中的元素按照值的大小进行排列

>>> numbers=[1, 5, 9, 2, 6, 8, 0]

>>> numbers

[1, 5, 9, 2, 6, 8, 0]

>>> numbers.sort()

>>> numbers

[0, 1, 2, 5, 6, 8, 9]

 

比较2个数值,com(a, b) 如果a>b则返回1, 如果a=b则返回0,如果a<b则返回-1。

>>> cmp(100, 50)

1

>>> cmp(100, 100)

0

>>> cmp(100, 200)

-1

 

 

[2020-06-21]python基础回顾

原文:https://www.cnblogs.com/liurong07/p/13173236.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!