Python元组与字符串操作(9)——随机数、元组、命名元组

随机数

import random  #导入random模块

randint(a,b) 返回[a,b]之间的整数

random.randint(0,9)

randrange([start],stop,[step]) 从指定范围内,按指定step基数递增的集合中,获取一个随机数,基数缺省为1

random.randrange(2,15,5)
7

choice(seq) 从非空序列的元素中随机挑选一个元素

random.choice(range(10))
random.choice([0,1,2,3,4,5,6,7,8,9])

list
= [0,1,2,3,4,5,6,7,8,9] random.choice(list)

random.shuffle(list) 就地打乱列表元素

list = [0,1,2,3,4,5,6,7,8,9]
random.shuffle(list)
list
[2, 4, 7, 0, 3, 9, 8, 6, 1, 5]

sample(population,k) 从样本空间或总体(序列或集合类型)中随机取出k个不同元素,返回一个新的列表

random.sample([0,1,2,3,4,5,6,7,8,9],2)
[5, 4]
random.sample([1,1,1,1],2)
[1, 1]

元组

tuple,有序的元素组成的集合,使用小括号()表示

元组是不可变的对象

元组的定义

tuple()    #空元组
t = tuple()
t = ()

t = tuple(range(1,7,2))
t = (2,4,6,3,4,2)

t = (1,)    #一个元素的元组定义,必须有逗号

t = (1,)*5
t = (1,2,3)*6

元组通过索引访问

tuple[index] 正负索引不可以超界,否则报异常IndexError

t = (1,2,3,4,5)

t[-2]
4

t[6]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-15-d806090743c9> in <module>
----> 1 t[6]

IndexError: tuple index out of range

元组不可改变,不支持元素赋值

t[-2] = 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-748d3b852e35> in <module>
----> 1 t[-2] = 5

TypeError: 'tuple' object does not support item assignment

元组中的列表可以改变

t = (1,2,3,[1,2,3],5)

t[-2][0] = 9
t
(1, 2, 3, [9, 2, 3], 5)
t = ([1,2],[3,4])*3
t
([1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4])

t[0][0] = 9
t
([9, 2], [3, 4], [9, 2], [3, 4], [9, 2], [3, 4])

元组查询

index(value,start,stop) #通过元素值value,从指定区间查找元组内的元素是否匹配,匹配第一个就立即返回索引,匹配不到报异常ValueError,时间复杂度O(n)

t = (2,3,4,5,6)
t.index(4,0,3)
2

count(value) #返回元组中元素值value匹配次数,时间复杂度O(n)

t = (2,3,4,5,6)
t.count(2)
1

len(tuple) #返回元素个数,时间复杂度O(1)

t = (2,3,4,5,6)
len(t)
5

命名元组

namedtuple(typename,field_names,verbose=False,rename=False)

定义一个元组的子类,并定义了字段

field_names可以是空白符或者逗号分割的字段的字符串,可以是字段的列表

from collections import namedtuple
# import collections
# collections.namedtuple()  #两种导入方法 point
= namedtuple('Point',['x','y']) point __main__.Point

定义2个学生

from collections import namedtuple

point = namedtuple('student',['name','age'])    #多种写法
# point = namedtuple('student','name,age')
# point = namedtuple('student','name age')

tom = point('tom',17)
tom
student(name='tom', age=17)

jerry = point('jerry',18)
jerry
student(name='jerry', age=18)
原文地址:https://www.cnblogs.com/omgasw/p/11646738.html