Home Archives Categories Tags

python学习笔记4

发布时间: 更新时间: 总字数:877 阅读时间:2m 作者: 分享

python学习笔记4

说明

  1. 分片
Tag = ‘abcdefg’
Tag[2:4]
  1. Python * 5
PythonPythonPythonPythonPython
  1. None 表示什么都没有
>>> s = [None]* 10

>>> s

[None, None, None, None, None, None, None, None, None, None]
  1. In
‘a’ in ‘abcdef’
True
  1. 内建函数:len,min,max

Len函数返回序列中所包含元素的数量

Min和max函数返回序列中的最大值和最小值

  1. List函数(使用于所有的类型的操作)

  2. 测试

[1, 2, 1]
>>> del x[2]
>>> x
[1, 2]
>>> x[1:]
SyntaxError: invalid syntax
>>> x[1:]
[2]
>>> x
[1, 2]
>>> x[1:1] = [2, 3, 4]
>>> x
[1, 2, 3, 4, 2]
>>> x[2:] = []
>>> x
[1, 2]
>>> x = [[1,2], 1, 1, [2, 1, [1, 2]]]
>>> x
[[1, 2], 1, 1, [2, 1, [1, 2]]]
>>> x.count(1)
2
>>> x.count([1, 2])
1
>>> x.append(3)
>>> x
[[1, 2], 1, 1, [2, 1, [1, 2]], 3]
>>> 
>>> a= [1, 2, 3]
>>> b = [3, 4, 5]
>>> a.append(b)
>>> a
[1, 2, 3, [3, 4, 5]]
>>> b
[3, 4, 5]
>>> id(a)
43400688
>>> a = [1, 2, 3]
>>> id(a)
43428440
>>> a.append(b)
>>> id(a)
43428440
>>> a
[1, 2, 3, [3, 4, 5]]
>>> a.extend(b)
>>> a
[1, 2, 3, [3, 4, 5], 3, 4, 5]
>>> a+b
[1, 2, 3, [3, 4, 5], 3, 4, 5, 3, 4, 5]
>>> a
[1, 2, 3, [3, 4, 5], 3, 4, 5]
>>> b
[3, 4, 5]
>>> 
>>> a = a + b
>>> a
[1, 2, 3, [3, 4, 5], 3, 4, 5, 3, 4, 5]
>>> b
[3, 4, 5]
>>> 
  1. Index
>>> str1 = ['we', 'are', 'ok']
>>> str1
['we', 'are', 'ok']
>>> str1.index ('we')
0
>>> str1.index ('abc')
Traceback (most recent call last):
 File "", line 1, in 
   str1.index ('abc')
ValueError: list.index(x): x not in list
>>> 
>>> str1
['we', 'are', 'ok']
>>> str1.insert(2, 'not')
>>> str1
['we', 'are', 'not', 'ok']
>>> 
  1. Pop移除
>>> x = [1, 2, 3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]
>>> 

注:

  • 栈,入栈:push(),append(),出栈pop,pop()
  • 队列,入:insert(0, …),出,pop(0)
  1. Remove()

  2. Reverse()反转

>>> x = [1, 2, 3, 4, 5]
>>> x
[1, 2, 3, 4, 5]
>>> x.reverse()
>>> x
[5, 4, 3, 2, 1]
>>> 
  1. Sort方法用于在原来位置对列表进行排序。注意内存是不变的。
>>> x = [1, 2, 3, 4, 5]
>>> x
[1, 2, 3, 4, 5]
>>> x.reverse()
>>> x
[5, 4, 3, 2, 1]
>>> x= [4, 6, 2, 1, 7, 9]
>>> x
[4, 6, 2, 1, 7, 9]
>>> id(x)
43269736
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
>>> id(x)
43269736
>>> 
分配地址y = x[:]
Sorted(‘python’)
>>> x
[4, 6, 2, 1, 7, 9]
>>> x
[4, 6, 2, 1, 7, 9]
>>> y = sorted(x)
>>> x
[4, 6, 2, 1, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9]
>>> 
  1. Cmp(x, y)
>>> cmp(42, 32)
1
>>> cmp(99, 100)
-1
>>> cmp(1, 1)
0
>>> 
>>> x
[4, 6, 2, 1, 7, 9]
>>> x.sort(cmp)
>>> x
[1, 2, 4, 6, 7, 9]
>>> 
>>> x.reverse()
>>> x
[9, 7, 6, 4, 2, 1]
>>> sorted(x).reverse()
>>> x
[9, 7, 6, 4, 2, 1]
>>> y
[1, 2, 4, 6, 7, 9]
>>> sorted(y).reverse()
>>> y
[1, 2, 4, 6, 7, 9]
>>> 
>>> y
[1, 2, 4, 6, 7, 9]
>>> y.sort(reverse = True)
>>> y
[9, 7, 6, 4, 2, 1]
>>> 
>>> str1
['we', 'are', 'not', 'ok']
>>> str1.sort(key = len)
>>> str1
['we', 'ok', 'are', 'not']
>>> 
  1. Tuple函数的功能与list函数基本上是一样的:以一个序列作为参数并把它转换为元组。
>>> tuple(y)
(9, 7, 6, 4, 2, 1)
>>> y
[9, 7, 6, 4, 2, 1]
>>> 

不返回值的方法:reverse、sort、

最新评论
加载中...