Python元組與字符串操做(9)——隨機數、元組、命名元組

隨機數

import random  #導入random模塊python

randint(a,b) 返回[a,b]之間的整數dom

random.randint(0,9)

randrange([start],stop,[step]) 從指定範圍內,按指定step基數遞增的集合中,獲取一個隨機數,基數缺省爲1spa

random.randrange(2,15,5)
7

choice(seq) 從非空序列的元素中隨機挑選一個元素code

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個不一樣元素,返回一個新的列表blog

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,有序的元素組成的集合,使用小括號()表示索引

元組是不可變的對象ip

元組的定義

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

元組不可改變,不支持元素賦值input

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)
相關文章
相關標籤/搜索