Python基础概念

  
python是一种弱类型语言,定义变量时直接赋值即可

a = 100
b = 'my string'
  • 字符串

三引号用于含有多行的字符串

c = '''my
string var'''

字符串可加

a = 'hello' + 'world'

字符串索引

a = 'hello' + 'world'
a[0] # 'h'
a[-1]  # 'd'
a[0:5]  # 'hello'
len(a)  # 11

字符串分割

a = 'hello' + 'world'
a.split()   #  ['hello','world']

['hello','world']

  • 列表

通过 [ ] 生成列表

a = [1, 'string', 3]
a + a  # [1, 'string', 3, 1, 'string', 3]

列表索引和长度同string一样,列表非列表元素的基础变量可通过append添加

a.append('world')
a  # [1, 'string', 3, 'world']
  • 集合set

集合通过 { } 创建,集合中不会有重复的元素

s = {1, 2, 3, 1}  ## {1, 2, 3}
len(s)   # 3

集合中添加元素

s.add(4)   #{1, 2, 3, 4}

集合有交、并、差、对称差等运算

a = {1, 2, 3}
b = {2, 3, 4}
a & b  # {2, 3}
a | b  #{1, 2, 3, 4}
a - b  #{1}
a ^ b  #{1, 4}
  • 字典Dictionary

字典通过{key:value}来生成dictionary

d = {'man' = 0, 'woman' = 1}
len(d)  # 2
d['man']   #查字典  0

修改键值和插入键值类似

d['man'] = 1
d['dog'] = 3

查看所有对应的内容通过调用方法

d.keys()   #查看所有的键  ['man', 'woman']
d.values()  #查看所有的值 [0, 1]
d.items()  #查看所有的项(包括键和键值)
  • 数组 (numpy array)

使用array需要导入numpy库,array可以进行很多列表没有的操作

from numpy import array #import numpy as np
a = array([1, 2, 3])  # 中间的可用小括号,中括号和大括号
b = np.arange(4).reshape(2, 2)
b
#array([1,2],
#[3,4])
  • 循环loop

str_num = '1 2 3'
fields = str_num.split()
fields      # ['1', '2', '3']
total = 0
for field in fields:
    total += int(field)
total   #6
#列表推导式法
numbers = [int(field) for field in fields]
numbers   # [1, 2, 3]
  • 文件操作

#write
f = open('data.txt', 'w')
f.write('1 2 3 4\n')
f.write('2 3 4 5\n')
f.close()

#read
f = open('data.txt')
data = []
for line in f:
    data.append([int(field) for field in line.split()])
f.close()
data
  • 定义函数Function

使用关键词def 定义函数

def poly(x, a, b, c):
    y = a * x ** 2 + b * x + c
    return y

x = 1
poly(x, 1, 2, 3)
###定义时也可设置默认值
def poly(x, a=1, b=2, c=3):
    y = a * x ** 2 + b * x + c
    return y

x = 1
poly(x, 1, 2)
#具有默认值的参数在调用时可重新赋值也可不填使用默认值
  • 类Class

用class来定义一个类。 Person(object)表示继承自object类; __init__函数用来初始化对象; self表示对象自身,类似于C Java里面this。

class Person(object):
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age
    def full_name(self):
        return self.first + ' ' + self.last

person = Person('some', 'one', 18)
person.first   #调用对象的属性'some'
person.full_name()  #调用对象的方法 'some one'
person.last = 'time'  #修改对象的属性
person.id = 234   #添加属性
posted @ 2019-07-09 09:22  breezezz  阅读(201)  评论(0编辑  收藏  举报