栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python复健】Python入门基础知识整理1

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python复健】Python入门基础知识整理1

目录

一、数据类型

1、数字类型(Numbers)

2、布尔类型(Booleans)

3、字符串类型(Strings)

二、容器

1、列表

2、字典

3、集合

4、元组

三、函数

1、函数定义

2、函数参数

四、类

总结


前言

距离上次学python时隔一年,现在学深度学习,进行一个python基础知识的复健。

主要从数据类型(数字 布尔 字符串)、容器(列表 字典 集合 元组)、函数、类四个方面整理。


一、数据类型

1、数字类型(Numbers)

代表整数和浮点数,原理与其它语言相同。

x=5             # 直接定义数字
print(x)        # 输出"5"
print(x+1)      # 直接做运算 输出"6"
print(x**2)     # 两个**表示幂 即5^2=25 输出"25"
x += 1          # x = x+1
x *= 2          # x = x*2
## python的数字类型比较特殊,没有x+和x-运算符
print(type(x))  # 输出""

y = 5.5
print(type(y))  # 输出""

2、布尔类型(Booleans)

pyhton中使用的是英文单词而不是符号

T = True          # 直接定义
F = False
print(type(T))    # 输出""
print(T and F)    # 与,输出"False"
print(T or F)     # 或,输出"True"
print(not F)      # 非,输出"True"
print(T != F)     # 输出"True"

3、字符串类型(Strings)
hello='hello'        
world = "world"     # 单双引号均可
print(hello)        # Prints "hello"
print(len(hello))   # 字符串长度;prints"5" 
hw=hello+world      # 字符串拼接直接使用+
print(hw)           # prints "hello world" 
hw12 ='%s %s %d' % (hello, world, 12) 
print(hw12)         # prints "hello world 12"

s = 'beautiful'
# 大小写变换
print(s.upper())         # prints"BEAUTIFUL"
print(s.capitalize())    # prints"Beautiful"

# 输出调整
print(len(s))            # prints"9"
print(s.rjust(11))       # prints"  beautiful"
print(s.center(11))      # prints" beautiful "
print(s.replace('iful','y'))   # prints"beauty"

print('  beauty  '.strip())    # prints"beauty"

二、容器

1、列表

列表其实就是Python中的数组,但是可以它可以动态的调整大小,并且可以包含不同类型的元素。

xs = [3, 1, 2]           # 创建一个列表
print(xs, xs[2])         # Prints "[3, 1, 2] 2"
print(xs[-1])            # 负数的索引代表从列表的最后开始算起;prints "2" 
xs[2]='foo'              # 列表可以包含不同类型的元素
print(xs)                # Prints "[3, 1, "foo']" 
xs.append('bar')         # 在列表的末尾添加新元素 
print(xs)                # Prints "[3, 1, "foo', 'bar']" 
x=xs.pop()               # 从列表的末尾删除元素并返回该元素
print(x,xs)              # Prints "bar [3, 1, 'foo']"

切片(Slicing): 除了一次访问一个列表元素之外,Python还提供了访问子列表的简明语法; 称为切片。

nums = list(range(5))       # range(x) int类型长为x的顺序数组 
print(nums)                 # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4])            # 获得索引为从2到4(不包含)的元素;([2:4]的形式左闭右开)
                            # prints "[2, 3]"
print(nums[2:])             # 索引从2到末尾;prints "[2, 3, 4]"
print(nums[:2])             # 索引从开始到2(不包含);prints"[0,1]"
print(nums[:])              # prints "[0, 1, 2, 3, 4]"
print(nums[:-1])            # 负数索引表示从末尾开始数; prints "[0, 1, 2, 3]"
nums[2:4]=[8,9]             # 直接修改
print(nums)                 # Prints "[0, 1, 8, 9, 4]"

循环(Loops):可以循环遍历列表的元素。

animals = ['cat', 'dog', 'monkey'] 
for animal in animals: 
    print(animal) 
# 逐行输出 "cat", "dog", "nonkey"

## 如果要访问循环体内每个元素的索引,使用内置的enumerate函数: 
for idx, animal in enumerate(animals): 
    print('#%d: %s' % (idx + 1, animal)) 
# 逐行输出:"#1: cat", "#2: dog", "#3: monkey"

for idx in enumerate(animals): 
    print(idx) 
# 输出:(0, 'cat')
        (1, 'dog')
        (2, 'monkey')

列表推导式(List comprehensions): 编程时,我们经常想要将一种数据转换为另 一种数据。列表推导式可以帮助我们使用更简介的代码来实现。

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] 
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]"

2、字典
d = {'cat': 'cute', 'dog': 'furry'}        
# 与列表使用[]定义不同,字典使用{}定义,格式为{key:value,...}
print(d['cat'])        # 从字典中获取键值为"cat"的值;输出:"cute"
print('cat'in d)       # 检查字典中是否含有键值"cat"(不能用于检查value);输出:"True"
d['fish']=wet          # 字典中增加新的对

## 字典的get函数:get()是查找并返回字典中的某个键的值,找到则返回该值,找不到则返回None。
print(d.get('monkey'))  # prints:"None"
print(d,get('fish'))    # prints:"wet"

## get()方法的自定义返回值:
## 字典方法get()可以有两个参数,第一个是必选参数key,第二个是可选参数,并且是可自定义的参数,是get()方法的返回值,即如果不写则get()方法默认返回None,如果要写,可自定义这个参数,get()方法将返回此自定义参数值。
print(d.get('fish','find nothing'))      # prints:"wet"
print(d.get('monkey','find nothing'))    # prints:"find nothing"   

# 删除字典中的对
del d['fish']
print(d.get('fish','find nothing'))    # prints:"find nothing"  

循环(Loops):选代词典中的键很容易:

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"

如果要访问键及其对应的值,请使用items方法:

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"

字典推导式(Dictionary comprehensions):类似于列表推导式:

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)"

3、集合

集合是不同元素的无序集合,不能含有相同的元素。

animals = {'cat', 'dog'}
print('cat' in animals)     # prints "True" 
print('fish' in animals)    # prints"False" 
animals.add('fish')         # 在集合中添加对 
print('fish' in animals)    # Prints "True" 
animals.add('cat')          # "cat"在集合中已经存在,并不能再次添加
print(len(animals))         # Prints "3" 
animals.remove('cat')       # 移除元素
print(len(animals))         # Prints "2"     

循环(Loops):遍历集合的语法与遍历列表的语法相同;但由于集合是无序的,因此不能假设访问集合元素的顺序:

animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals): 
    print('#%d:%s' % (idx+1,animal)) 
# Prints :"#1: fish", "#2: dog", "#3: cat"

集合推导式(Set comprehensions):和列表和字典的推导式类似:

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

4、元组

元组是(不可变的)有序值列表。元组在很多方面类似于列表;但有一个最重要的区别是元组可以用作字典中的键和集合的元素,而列表则不能。

d={(x,x+1): x for x in range(10)}    # 创建一个以元组作为键值的字典
t=(5,6)          # 创建一个元组
print(type(t))   # Prints:"" 
print(d[t])      # Prints "5"  
print(d[(1, 2)]) # Prints "1"

三、函数

1、函数定义

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

def sign(x): 
    if x > 0:
        return "positive"
    elif x < 0:
        return "negative" 
    else: 
        return "zero" 

or x in [-1, 0, 1]: 
    print(sign(x)) 
# Prints "negative", "zero", "positive"

2、函数参数

经常定义函数来获取可选的关键字参数

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!"

四、类
class Greeter(object): 

# Constructor 
def _init (self, name): 
    self.name = name      # Create an instance variable 

# Instance method 
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!"

总结

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/744526.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号