python程序练习

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]
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,172评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,346评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,788评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,299评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,409评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,467评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,476评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,262评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,699评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,994评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,167评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,827评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,499评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,149评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,387评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,028评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,055评论 2 352

推荐阅读更多精彩内容

  • 问题2: Fibonacci序列中的每个新术语都是通过添加前两个术语生成的。 从1和2开始,前10个术语将是:1,...
    珍惜妮阅读 148评论 0 0
  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,145评论 0 13
  • 该文章为转载文章,作者简介:汪剑,现在在出门问问负责推荐与个性化。曾在微软雅虎工作,从事过搜索和推荐相关工作。 T...
    名字真的不重要阅读 5,241评论 0 3
  • 与 TensorFlow 的初次相遇 https://jorditorres.org/wp-content/upl...
    布客飞龙阅读 3,943评论 2 89
  • 绿萝的花园已经出来大致的轮廓了,小小地激动了一把。只有这样的时候,自己才会知道,是多么的爱着花园。眼前的一切,远比...
    朱泓默阅读 411评论 7 5