【CS231n学习笔记】1. python numpy 之Python

https://zhuanlan.zhihu.com/p/20878530?refer=intelligentunit

python

基本数据类型

数字

x = 3
print(type(x))
x -= 0.1
x **= 2  # 乘方
print(type(x))
print(x)
输出:
<class 'int'>
<class 'float'>
8.41

布尔

x = True
y = False
print(x and y)
print(x or y)
print(not x)
print(x == y)
print(x != y)
输出:
False
True
False
False
True

字符串

x = "hello world"
print(len(x))  # 长度
print(x.capitalize())  # 似乎是首字母大写
print(x.upper())  # 全大写

# 右对齐(左边填空格
print("******".rjust(20))
print("*****".rjust(20))
print("****".rjust(20))
print("***".rjust(20))
print("**".rjust(20))
print("*".rjust(20))

# 居中
print("*********".center(20))
print("*******".center(20))
print("*****".center(20))
print("***".center(20))
print("*".center(20))

print("*********".center(20).replace(" ", "-"))  # 替换

print("     hello wo rl d    ".strip())  # 删除头尾空格
输出:
11
Hello world
HELLO WORLD
              ******
               *****
                ****
                 ***
                  **
                   *
     *********      
      *******       
       *****        
        ***         
         *          
-----*********------
hello wo rl d

容器

List

x = [1, 2, 3, 4]
print(x[-1])  # -1,最后一个元素,喵喵喵喵喵?有这种操作?

# 和vector的pop_back()一样
print(x.pop())
print(x)

# 毛线都能往里塞
x.append("123")
x.append([1, 2, 3])
print(x)
输出:
4
4
[1, 2, 3]
[1, 2, 3, '123', [1, 2, 3]]

 切片

x = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(x)

print(x[2:4])  # x[2],x[3]
print(x[2:])  # x[2~结尾]
print(x[:4])  # x[0~3]
print(x[:-1])  # 除了最后一个,因为-1代表最后一个下标,输出到-1前一个
输出
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[2, 3]
[2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6, 7]

 遍历

x = ["sdf", "dsfdfs", "werc"]
for i in x:
    print(i)

# 新操作,这样就有序号了
for i, t in enumerate(x):
    print("%d %s" % (i, t))
输出
sdf
dsfdfs
werc
0 sdf
1 dsfdfs
2 werc

列表推导

x = [1, 2, 3, 4, 5]
xx = [t for t in x if t % 2 == 0]
print(xx)

xx = [t ** 2 for t in x]
print(xx)
输出
[2, 4]
[1, 4, 9, 16, 25]

 字典

x = {1: "11", 2: "22"}

# 设置默认,已经有了就没用了
x.setdefault(2, "0")
x.setdefault(3, "0")
print(x)

del x[3]
print(x)
x[3] = "3"
print(x)

print(x.get(4))
print(x.get(4, 0))  # 没有的话,按设置的默认值来
# print(x[4]) 是不行的

#遍历
for i in x:
    print(i, x[i])
输出:
{1: '11', 2: '22', 3: '0'}
{1: '11', 2: '22'}
{1: '11', 2: '22', 3: '3'}
None
0
1 11
2 22
3 3

class Test:
    name = ""

    def __init__(self, name="123"):
        self.name = name

    def print(self):
        print(self.name)


class Test2(Test):  # 继承
    def __init__(self, name="1234"):
        Test.__init__(self, name)
        return


test = Test()
test.print()

test = Test("hello")
test.print()

test2 = Test2()
test2.print()
输出:
123 hello 1234
原文地址:https://www.cnblogs.com/dreamingsheep/p/7107656.html