Python入门速成(基于Stanford计算机视cs231n课程tutorial)

Python入门速成(基于Stanford计算机视cs231n课程tutorial),第1张

斯坦福计算机视觉提供tutorial:Python Numpy Tutorial (with Jupyter and Colab)

目录

Basic data types(基本数据类型 )

Number

Boolean

Strings

Containers 容器

Lists

1. 基本 *** 作 

2.  切片

3.  for循环输出所有元素

4. 高级应用

Dictionaries

Sets 集合 

Tuples元组 

Function 

Classes 类


Basic data types(基本数据类型 ) Number
#numbers
x=3
print(x,type(x))
print(x+1)
print(x*2)
print(x**2) #2倍
y=2.5
print(y,type(y))
print(y,y*2,y**2)

python没有x++,x--等二元 *** 作符

Boolean
#booleans
t,f=True,False
print(t)
print(f)
t = True
f = False
print(type(t)) # Prints ""
print(t and f) # Logical AND; prints "False"
print(t or f)  # Logical OR; prints "True"
print(not t)   # Logical NOT; prints "False"
print(t != f)  # Logical XOR; prints "True"
Strings
hello='hello'
world='world'
print(hello,len(world))

hw = hello +' '+world #字符串连接
print(hw)

hw12='{}-{}-{}'.format(hello,world,12)#字符串格式化
print(hw12)
hw13='{}.{}.{}'.format(hello,world,13)#字符串格式化
print(hw13)

hello 5
hello world
hello-world-12
hello.world.13

#strings
s='hello'
print(s.capitalize()) #首字母大写
print(s.upper()) #全部大写
print(s.rjust(7)) #右移7个字符,以空格占位
print(s.center(7)) #居中字符一空格占位
print(s.replace('l','(ell)')) #替换,把所有l替换成(ell)
print('  world  '.strip()) #除去字符串开头和结尾的空格

 Hello
HELLO
  hello
 hello 
he(ell)(ell)o
world

Containers 容器 Lists

A list is the Python equivalent of an array, but is resizeable and can contain elements of different types. Python中的列表相当于数组,但是列表可以改变长度并且可以容纳不同类型的元素

1. 基本 *** 作 
xs=[3,2,1]
print(xs,type(xs))
print(xs,xs[2]) #打印全部列表和下标为2的列表

xs[2]='hello'
print(xs)

xs.append('bar') #在列表尾部加入新元素
print(xs)

x=xs.pop() #移除列表中的最后一个元素
print(x,xs)

[3, 2, 1]
[3, 2, 1] 1
[3, 2, 'hello']
[3, 2, 'hello', 'bar']
bar [3, 2, 'hello']

2.  切片
nums = list(range(5))    # range is a built-in function that creates a list of integers
print(nums)         # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4])    # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])     # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])     # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])      # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print(nums[:-1])    # Slice indices can be negative; prints ["0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
print(nums)         # Prints "[0, 1, 8, 9, 4]"

1. range(5) #生成0,4的数字

2. nums[2:4]   #取下标为 [2,4)的元素

3. nums[ :2]  #取下标为[0,2) 的元素

4. nums[2:]  #取下标从2到最后的元素

5. nums[:]   #取全部元素

6. nums[-1]   #减少打印一个元素

7. 把下标为2和3的元素替换为8和9

3.  for循环输出所有元素
animals = ['cat','dog','bird']
for animal in animals:
    print(animal)

cat
dog
bird

animals = ['cat','dog','bird']
for i,animal in enumerate(animals):
    print('#{}:{}'.format(i,animal))

输出索引和对应的元素 

 #1:cat
#2:dog
#3:bird

4. 高级应用

对list中的值进行改变: 

nums= [0,1,2,3,4]
squares = []
for x in nums:
    squares.append(x**2) #append附加
print(squares)

 使用list comprehension:

nums= [0,1,2,3,4]
squares = [x**2 for x in nums]
print(squares)

#附加条件
evenSquares= [x**2 for x in nums if x%2==0]
print(evenSquares)

[0, 1, 4, 9, 16]
[0, 4, 16]

Dictionaries

A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript.

  • 字典相当于java或c++中的map,有key索引值和value对应内容值
d={'cat':'cute','dog':'furry'}
print(d['cat'])
print('cute' in d) #查看key值是否在dictionary里,是返回true,否返回false

cute
False

get()方法语法:
dict.get(key, default=None)
key -- 字典中要查找的键。
default -- 如果指定键的值不存在时,返回该默认值

d={'cat':'cute','dog':'furry'}

d['fish'] = 'wet'
print(d['fish'])

print(d.get('monkey','N/A'))
print(d.get('fish'))
print(d)

wet
N/A
wet
{'cat': 'cute', 'dog': 'furry', 'fish': 'wet'}

d={'cat':'cute','dog':'furry'}

d['fish'] = 'wet'
print(d['fish'])

del d['fish'] #删除
print(d.get('fish','N/A')) #因为字典中没有fish值了,所以输出设置的默认N/A值

print(d)

 wet
N/A
{'cat': 'cute', 'dog': 'furry'}

迭代器访问字典的key和value

d={'person':2,'cat':4,'spider':8}
for animal,legs in d.items():
    print('A {} has {} legs'.format(animal,legs))

 A person has 2 legs
A cat has 4 legs
A spider has 8 legs

nums = [0,1,2,3,4]
even_num_to_square = {x: x**2 for x in nums if x%2==0}
print(even_num_to_square)

 {0: 0, 2: 4, 4: 16}

Sets 集合 

一组无序的元素集合 

animals = {'cat','dog'}
print('cat' in animals) #打印cat是否在集合中,是:打印true
print('fish' in animals) #打印fish是否在集合中,否:打印false

animals.add('fish') #在集合中添加元素
print('fish' in animals)
print(len(animals))  #输出集合中的元素个数

animals.add('cat') #在集合中添加已有的元素,集合不做改变,元素个数也不会变化
print(len(animals))
animals.remove('cat') #删除集合中的值
print(len(animals))

True
False
True
3
3
2

使用for输出集合中的元素和下标,由于 集合中的元素存储是无序的,因此输出的顺序也是不确定的。

animals = {'cat','dog','fish','bird','horse'}
for i,animal in enumerate(animals):
    print('#{}:{}'.format(i,animal))

 #0:horse
#1:dog
#2:cat
#3:bird
#4:fish

Tuples元组 

A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot.

  • 元组是一系列可修改、有序的元素,与列表类似,但是元组可以被用作字典的key值和集合里的元素,列表则不能
d={(x,x+1):x for x in range(10)} #创建一个key值为元组的字典
print(d)
t=(5,6) #创建一个元组
print(type(t))
print(d[t])
print(d[(1,2)])

{(0, 1): 0, (1, 2): 1, (2, 3): 2, (3, 4): 3, (4, 5): 4, (5, 6): 5, (6, 7): 6, (7, 8): 7, (8, 9): 8, (9, 10): 9}

5
1

Function 

Python functions are defined using the def keyword

  • Python使用def关键字来定义函数
def sign(x):
    if x>0:
        return 'positive'
    elif x<0:
        return 'negative'
    else:
        return 'zero'

for x in [-1,0,1]:
    print(sign(x))

negative
zero
positive

函数中的参数可以是默认的或者可选择的 

def hello(name,loud=False):
    if loud:
        print('hello,{},please be quiet.'.format(name))
    else:
        print('hello,{},you are welcomed!'.format(name))

hello('Bob')
hello('Frank',loud=True)

Classes 类

Python使用class关键字来定义类

class Greeter:
    #构造函数
    def __init__(self,name):
        self.name= name
        
    #方法
    def greet(self,loud=False):
        if loud:
            print('hello,{},please be quiet.'.format(self.name))
        else:
            print('hello,{},you are welcomed!'.format(self.name))

g = Greeter('Frank')
g.greet()
g.greet(moud=True)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/786339.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存