CS231n,你还需要了解点Python

Python


讲述点⬇
Python基本体系


基本数据类型-Basic data types

同c++明显不同的是,python无需在变量前声明变量的数据类型,python会自动根据数据的类型进行归类。

python无自增(++)和自减符(–)。

python中进行与或等操作的操作符是其英文单词,而非c++之类的标识符(||、&&等)

# 计算操作

x = 3
print(type(x)) # Prints "<class 'int'>"
print(x)       # Prints "3"
print(x + 1)   # Addition; prints "4"
print(x - 1)   # Subtraction; prints "2"
print(x * 2)   # Multiplication; prints "6"
print(x ** 2)  # Exponentiation; prints "9"
x += 1
print(x)  # Prints "4"
x *= 2
print(x)  # Prints "8"
y = 2.5
print(type(y)) # Prints "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"
#逻辑判断

t = True
f = False
print(type(t)) # Prints "<class 'bool'>"
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"
#字符串操作

hello = 'hello'    # String literals can use single quotes
world = "world"    # or double quotes; it does not matter.
print(hello)       # Prints "hello"
print(len(hello))  # String length; prints "5"
hw = hello + ' ' + world  # String concatenation
print(hw)  # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting
print(hw12)  # prints "hello world 12"
#字符串转换

s = "hello"
print(s.capitalize())  # Capitalize a string; prints "Hello"
print(s.upper())       # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7))      # Right-justify a string, padding with spaces; prints "  hello"
print(s.center(7))     # Center a string, padding with spaces; prints " hello "
print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another;
                                # prints "he(ell)(ell)o"
print('  world '.strip())  # Strip leading and trailing whitespace; prints "world"

容器-Containers

Lists ~~ 列表

[-1]表示指向列表的最后一个元素。

可变长的。

虽然可变长,但不能直接通过x[len(x)]=10来增加超出范围的元素。只能通过x.append(10)来增加!

可容纳不同类型的数据。

访问数组元素方式更加简洁。

循环的in表达。

支持[ ]索引中进行循环操作和判断操作!

所谓Lists在python中就是数组的含义,但是是可变长的可容纳不同类型的

#单个数组元素的操作

xs = [3, 1, 2]    # Create a list
print(xs, xs[2])  # Prints "[3, 1, 2] 2"
print(xs[-1])     # Negative indices count from the end of the list; prints "2"
xs[2] = 'foo'     # Lists can contain elements of different types
print(xs)         # Prints "[3, 1, 'foo']"
xs.append('bar')  # Add a new element to the end of the list
print(xs)         # Prints "[3, 1, 'foo', 'bar']"
x = xs.pop()      # Remove and return the last element of the list
print(x, xs)      # Prints "bar [3, 1, 'foo']"
#对数组连续的块操作

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]"
#基于数组循环之直接取元素

animals1 = ['cat', 'dog', 'monkey']
for animal in animals1:
    print(animal)
# Prints "cat", "dog", "monkey", each on its own line.


#基于数组循环之下标索引

animals2 = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals2): #Function enumerate()
    print('#%d: %s' % (idx + 1, animal))
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
#一般计算方法

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


#[]中进行循环操作

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


#[]中进行循环操作和判断操作

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)  # Prints "[0, 4, 16]"
Dictionaries ~~ 字典

存放(Key,Value)的容器。即类是由关键码Key来找到键值Value的一个关系。

通过 Key:Value 的形式表示关系。

也是可变长的,但是可直接Dic[Key]=Value来增加。该语句表示有该Key则修改其对应的Value值,无则增加Key-Value值。

循环关系类似Lists。

#字典基本操作

d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
print(d['cat'])       # Get an entry from a dictionary; prints "cute"
print('cat' in d)     # Check if a dictionary has a given key; prints "True"
d['fish'] = 'wet'     # Set an entry in a dictionary
print(d['fish'])      # Prints "wet"
# print(d['monkey'])  # KeyError: 'monkey' not a key of d
print(d.get('monkey', 'N/A'))  # Get an element with a default; prints "N/A"
print(d.get('fish', 'N/A'))    # Get an element with a default; prints "wet"
del d['fish']         # Remove an element from a dictionary
print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"
#对字典的循环取值的方法一

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
    legs = d[animal]
    print('A %s has %d legs' % (animal, legs))
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"


#对字典的循环取值的方法二--用到item()函数

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
    print('A %s has %d legs' % (animal, legs))
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"
#方法类似Lists,允许更简单的构造字典。

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)  # Prints "{0: 0, 2: 4, 4: 16}"
Sets ~~ 集合

集合是不同元素的一个无序的集合。通俗讲,即不能通过下标索引的方式找到之对应的元素值,

是可变长的及可移除的

循环关系类似Lists。

#Sets的基本操作

animals = {'cat', 'dog'}
print('cat' in animals)   # Check if an element is in a set; prints "True"
print('fish' in animals)  # prints "False"
animals.add('fish')       # Add an element to a set
print('fish' in animals)  # Prints "True"
print(len(animals))       # Number of elements in a set; prints "3"
animals.add('cat')        # Adding an element that is already in the set does nothing
print(len(animals))       # Prints "3"
animals.remove('cat')     # Remove an element from a set
print(len(animals))       # Prints "2"
#循环取值的方式

animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))
# Prints "#1: fish", "#2: dog", "#3: cat"
#对元素的操作性循环

from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)  # Prints "{0, 1, 2, 3, 4, 5}"
Tuples ~~ 元组

元组是不可变的一个的列表(不能有添加,删除,和修改的操作)。

固定的,一旦生成就不能变(除了特殊情况–元素是一个对象的引用时,引用的对象是可以被修改的)

循环关系类似Lists。

元组可以用作字典中的Key和Sets的元素,而列表不能。

#该元组用于字典中的Key与Set的元素

d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
#{(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}
t = (5, 6)        # Create a tuple
print(type(t))    # Prints "<class 'tuple'>"
print(d[t])       # Prints "5"
print(d[(1, 2)])  # Prints "1"

函数-Functions

使用关键字 def 来定义函数。

函数名后接符号 开启函数体,靠缩进判断何时结束(事实上python就是靠缩进来判断,如if,for的有效操作域等)。

函数的参数也类似C++,也可以有默认参数。

#定义一个判断正负的函数
#注意缩进量!

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))
# Prints "negative", "zero", "positive"
#定义一个带默认形参的函数

def hello(name, loud=False):
    if loud:
        print('HELLO, %s!' % name.upper())
    else:
        print('Hello, %s' % name)

hello('Bob') # Prints "Hello, Bob"
hello('Fred', loud=True)  # Prints "HELLO, FRED!"

类-Classes

有C++或Java基础的应该很好理解什么是类。我就不详细说了。

#类的构造方法

class Greeter(object):

    # 构造函数
    def __init__(self, name):
        self.name = name  # Create an instance variable

    # 示例函数
    def greet(self, loud=False):
        if loud:
            print('HELLO, %s!' % self.name.upper())
        else:
            print('Hello, %s' % self.name)

#使用上述定义的类
g = Greeter('Fred')  # Construct an instance of the Greeter class
g.greet()            # Call an instance method; prints "Hello, Fred"
g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"

上述示例代码均来自 CS231n-Python Numpy Tutorial

猜你喜欢

转载自blog.csdn.net/hacker_Dem_br/article/details/86412127