Python基本数据生成
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:
if conditionN: s.append(expression)
还是来看一些基本的例子:
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
这两个基本上都是在循环的时候用。
for i in range(0, 100):
print i
for i in xrange(0, 100):
print i
这两个输出的结果都是一样的,实际上有很多不同,range会直接生成一个list对象:
a = range(0,100)
printtype(a)
print a
print a[0], a[1]
而xrange则不会直接生成一个list,而是每次调用返回其中的一个值
a = xrange(0,100)
print type(a)
print a
print 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]
>>>
产生二维数组并初始化:
>>> lists = [[] for i in range(3)]
>>> lists[0].append(1)
>>> lists[0].append(2)
>>> lists[0].append(3)
>>> lists[1] = [4,5,6]
>>> print lists
[[1, 2, 3], [4, 5, 6], []]
>>> lists2 = [([0]*3) for i in range(3)]
>>> print lists2
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>>
以上是 Python基本数据生成 的全部内容, 来源链接: utcz.com/z/388872.html