Python基本資料生成

2022-07-03 17:48:16 字數 2872 閱讀 9356

1. 隨機函式的使用

>>>random.random()

# random float x, 0.0 <= x < 1.0

0.37444887175646646

>>>

random

.uniform(1,

10) 

# random float x, 1.0 <= x < 10.0

1.1800146073117523

>>>

random.randint(1, 10)

# integer from 1 to 10, endpoints included

7>>>

random.randrange(0,

101, 2) 

#even integer from 0 to 100

26>>>

random.choice(

'abcdefghij') #

choose a random element

'c'>>>

items =[

1, 2,

3, 4,

5, 6,

7]>>>

random.shuffle(items)

>>>

items

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

>>>random.sample([1,

2, 3,

4, 5], 3) 

#choose 3 elements

[4, 1, 5]

2. 列表推導(list comprehesion)

列表推導的一般語法如下:

[expression

for item1 in iterable1 if condition1

for item2 in iterable2 if condition2

for itemn in iterablen if conditionn ]

大致等價於:

s =

for item1 in iterable1:

if condition1:

for item2 in iterable2:

if condition2:

for itemn in iterablen:

還是來看一些基本的例子:

a = [-3,5,2,-10,7,8]

b = 'abc'

c = [2*s for s in a]#c = [-6,10,4,-20,14,16]

d = [s for s in a if s >= 0]#d = [5,2,7,8]

e = [(x,y) for x in a

for y in b              

if x > 0 ]             

#e = [(5,'a'),(5,'b'),(5,'c'),(2,'a'),(2,'b'),(2,'c'), (7,'a'),(7,'b'),(7,'c'),(8,'a'),(8,'b'),(8,'c')]

f = [(1,2), (3,4), (5,6)]

g = [math.sqrt(x*x+y*y) for x,y in f]

#f = [2.23606, 5.0, 7.81024]

3.range 與 xrange

這兩個基本上都是在迴圈的時候用。

fori

in range(0

, 100):

print

ifor

i in 

xrange(0

, 100):

print

i這兩個輸出的結果都是一樣的,實際上有很多不同,

range

會直接生成乙個

list

物件:a =

range(0

,100)

print

type(a)

print

aprint

a[0], a[1]

而xrange

則不會直接生成乙個

list

,而是每次呼叫返回其中的乙個值

a =

xrange(0

,100)

print 

type(a)

print

aprint

a[0], a[1]

所以xrange

做迴圈的效能比

range

好,尤其是返回很大的時候!

盡量用xrange

吧,除非你是要返回乙個列表。

4. 一維與二維陣列的生成

產生一維陣列並初始化:

>>> initv = 0

>>> list_len = 5

>>> sp_list = [initv for i in xrange(10)]

>>> print sp_list

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

>>> sp_list2 = [initv] * list_len

>>> print sp_list2

[0, 0, 0, 0, 0]

>>>

產生二維陣列並初始化:

python基本數 python基本資料型別

1.數字 int 數字又分整型和浮點型,在python中宣告變數是不用宣告所以自己就會識別 a 10 整型 a1 1.24 浮點型 支援科學計數法,將10用e來代替 2.字串 str 在python中用引號引起來的就是字串,而且單引號和雙引號並沒有什麼區別 a string a1 string a2...

Python基本資料一

變數資料型別0 1 python基本資料型別包括了 數字型別,布林型,字串,列表,元組,字典,集合。一 檢視資料型別的方法 type 檢視資料型別 temp hello t type temp print t help,type 檢視資料型別下的全部方式 help type temp dir 檢視類...

python 型別 Python語言基本資料型別

本文主要向大家介紹了python語言基本資料型別,通過具體的內容向大家展示,希望對大家學習python語言有所幫助。python標準資料型別 有六個標準的資料型別 1 number 數字 2 string 字串 3 tuple 元組 4 list 列表 5 dict 字典 6 sets 集合 pyt...