美文网首页
python程序练习

python程序练习

作者: 流星小子 | 来源:发表于2018-10-15 15:41 被阅读0次
import numpy as np

生成元素全为0的二维张量,两个维度分别为3,4

np.zeros((3,4))
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])

生成三维的随机张量,三个维度分别为2,3,4

np.random.rand(2,3,4)
array([[[0.1477983 , 0.40141709, 0.85224419, 0.38584974],
        [0.24829636, 0.27591131, 0.26122221, 0.2995639 ],
        [0.93788947, 0.72531966, 0.27450982, 0.37431617]],

       [[0.92417031, 0.98691281, 0.29320554, 0.5915986 ],
        [0.76867925, 0.40096397, 0.31562832, 0.59135643],
        [0.60332   , 0.48597609, 0.8636971 , 0.39562407]]])

方阵:行数和列数相等的矩阵

np.eye(4)
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])

reshape:在数学中并没有reshape运算,但是在Numpy和Tensorflow等运算库中是一个非常常用的运算,用来改变一个张量的维度数和每个维度的大小,例如一个10x10的图片在保存时直接保存为一个包含100个元素的序列,在读取后就可以使用reshape将其从1x100变换为10x10,示例如下

x= np.arange(12)

生成一个包含整数0-11的向量

x
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
x.shape
(12,)
x = x.reshape(1,12)
x
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]])
x= x.reshape(3,4)
x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
x = np.arange(5).reshape(1,-1)
x
array([[0, 1, 2, 3, 4]])
x.T
array([[0],
       [1],
       [2],
       [3],
       [4]])
A = np.arange(12).reshape(3,4)
A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
A.T
array([[ 0,  4,  8],
       [ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11]])

生成234的张量

B = np.arange(24).reshape(2,3,4)
B
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

将B的01 两个维度转置

B.transpose(1,0,2)
array([[[ 0,  1,  2,  3],
        [12, 13, 14, 15]],

       [[ 4,  5,  6,  7],
        [16, 17, 18, 19]],

       [[ 8,  9, 10, 11],
        [20, 21, 22, 23]]])
 x = np.ones((1, 2, 3))
x
array([[[1., 1., 1.],
        [1., 1., 1.]]])
x.shape
(1, 2, 3)
np.transpose(x,(1,0,2))
array([[[1., 1., 1.]],

       [[1., 1., 1.]]])
np.transpose(x,(1,0,2)).shape
(2, 1, 3)
A= np.arange(6).reshape(3,2)
B = np.arange(6).reshape(2,3)
A
array([[0, 1],
       [2, 3],
       [4, 5]])
B
array([[0, 1, 2],
       [3, 4, 5]])
np.matmul(A,B)
array([[ 3,  4,  5],
       [ 9, 14, 19],
       [15, 24, 33]])
A = np.arange(6).reshape(3,2)
A
array([[0, 1],
       [2, 3],
       [4, 5]])
A*A
array([[ 0,  1],
       [ 4,  9],
       [16, 25]])
A+A
array([[ 0,  2],
       [ 4,  6],
       [ 8, 10]])
A= np.arange(4).reshape(2,2)
A
array([[0, 1],
       [2, 3]])
np.linalg.inv(A)
array([[-1.5,  0.5],
       [ 1. ,  0. ]])

字符串列表拼接

seeds = ["sesame","sunflower"]
seeds += ["pumpkin"]
seeds
['sesame', 'sunflower', 'pumpkin']
m = [5,9]
m += [6]
m
[5, 9, 6]
seeds += [5]
seeds
['sesame', 'sunflower', 'pumpkin', 5]
seeds.append("durian")
seeds
['sesame', 'sunflower', 'pumpkin', 5, 'd', 'u', 'r', 'i', 'a', 'n', 'durian']
print("Type integers,each followed by Enter; or just Enter to finish")
total = 0
count = 0
while True:
    line = input("Integer: ")
    if line:
        try:
            number =int(line)
        except ValueError as err:
            print(err)
            continue
        total += number
        count += 1
    else:
        break
if count:
    print("count=",count, "total =", total,"mean=", total/count)
Type integers,each followed by Enter; or just Enter to finish
Integer: 3
Integer: 4
Integer: a
invalid literal for int() with base 10: 'a'
Integer: 
count= 2 total = 7 mean= 3.5

函数的创建与调用

def functionName(arguments):

suite

def get_int(msg = 0):
    while True:
        try:
            i=int(input(msg))
            return i
        except ValueError as err:
            print(err)
get_int()
03





3
age = get_int("enter your age:")
enter your age:23
import sys
print(sys.argv)
['C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py', '-f', 'C:\\Users\\acer\\AppData\\Roaming\\jupyter\\runtime\\kernel-c140e89f-7532-424b-a3fc-8811de1dff5c.json']

模块中函数调用格式为 moduleName.functionName(arguments)

import random
x = random.randint(1,6)
x
2
x
2
x
2
x
2
x = random.randint(1,6)
x
1
y =random.choice(["apple","banana","cherry","durian"])
y
'apple'
y =random.choice(["apple","banana","cherry","durian"])
y
'durian'
y
'apple'
"917.5".isdigit()
False
"203".isdigit()
True
"-2".isdigit()
False
record ="Leo Tolstoy*1828-8-28*1910-11-20"
fields =record.split("*")
fields
['Leo Tolstoy', '1828-8-28', '1910-11-20']
born = fields[1].split("-")
born
['1828', '8', '28']
died = fields[2].split("-")
died
['1910', '11', '20']
print("lived about",int(died[0])- int(born[0]),"years")
lived about 82 years
"The novel '{0}' was published in {1}".format("Hard Times",1854)
"The novel 'Hard Times' was published in 1854"
"{who} turned {age} this year".format(who="She",age=88)
'She turned 88 this year'
"The {who} was {0} last week".format(12,who="boy")
'The boy was 12 last week'
stock =["paper","envelopes","notepads","pens","paper clips"]
"We have {0[1]} and {0[2]} in stock".format(stock)
'We have envelopes and notepads in stock'
d= dict(animal="elephant",weight=12000)
"The {0[animal]} weighs {0[weight]}kg".format(d)
'The elephant weighs 12000kg'
element = "Silver"
number = 47
"Element {number} is {element}".format(**locals())
'Element 47 is Silver'
"The {animal} weighs {weight}kg".format(**d)
'The elephant weighs 12000kg'
import decimal
decimal.Decimal("3.4084")
Decimal('3.4084')
print(decimal.Decimal("3.4084"))
3.4084
def f(x):
    return x,x **2
for x,y in ((1,1),(2,4),(3,9)):
    print(x,y)
1 1
2 4
3 9
things = (1,-7.5,("pea",(5,"Xyz"),"queue"))
things[2][1][1]
'Xyz'
things[2][1][1][2]
'z'
MANUFACTURER,MODEL,SEATING =(0,1,2)
MANUFACTURER
0
a,b =(3,4)
a,b = (b,a)
a,b
(4, 3)
import math
math.hypot(3,4) # 求两点之间的距离
5.0
import collections
Sale = collections.namedtuple("Sale","productid customerid date quantity price")
Sale
__main__.Sale
sales =[]
sales.append(Sale(432,921,"2008-09-14",3,7.99))
sales.append(Sale(419,874,"2008-09-15",1,18.49))

total = 0
for sale in sales:
    total += sale.quantity * sale.price
print("Total ${0:.2f}".format(total))
Total $42.46
Aircraft = collections.namedtuple("Aircraft","manufacturer model seating")
Seating = collections.namedtuple("Seating","minimum maximum")
aircraft =Aircraft("Airbus","A320-200",Seating(100,220))
aircraft
Aircraft(manufacturer='Airbus', model='A320-200', seating=Seating(minimum=100, maximum=220))
aircraft.seating.maximum
220
print("{0} {1}".format(aircraft.manufacturer,aircraft.model))
Airbus A320-200
"{0.manufacturer} {0.model}".format(aircraft)
'Airbus A320-200'
"{manufacturer} {model}".format(**aircraft._asdict())
'Airbus A320-200'
first,*rest =[9,2,-4,8,7] # 带星号表达式
first,rest
(9, [2, -4, 8, 7])
first,*mid,last = "Charles Philip Arthur George Windsor".split()
first,mid,last
('Charles', ['Philip', 'Arthur', 'George'], 'Windsor')
x= 8143 
x
8143
del x
L =["yes","my","name"]
for i in range(len(L)):
    print(L[i])
yes
my
name
a = range(len(L))
a
range(0, 3)
numbers =[1,2,3,4]
for i in range(len(numbers)):
    numbers[i] += 1
numbers
[2, 3, 4, 5]

相关文章

网友评论

      本文标题:python程序练习

      本文链接:https://www.haomeiwen.com/subject/hgbfzftx.html