Python介绍
Python是一种高级的、动态类型的多范型编程语言。现在常用的Python版本是Python3.x。
Python代码通常被认为是伪代码,因为在简明易懂的几行代码中可以表达出非常强大的思想。
举例说明,下面是Python中经典的快速排序算法的实现:
>>> def quicksort(arr):
if len(arr)<=1:
return arr
pivot = arr[len(arr)//2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
>>> print(quicksort([3,6,8,10,1,2,1]))
[1, 1, 2, 3, 6, 8, 10]
基本数据类型
python的基本数据有整型、浮点型、布尔类型、strings类型,用法与其他编程语言相似。
python没有自加自减的操作符,即python中不存在x++或是x–。
‘/ ‘就表示浮点数除法,返回浮点结果,’ // ‘表示整数除法,**表示幂次方。
python的单行注释是以 # 开头,多行注释是用三引号”’ ”’包含的。
数值计算
>>> x=3
>>> print(type(x))
<class 'int'>
>>> print(x)
3
>>> print(x+1)
4
>>> print(x-1)
2
>>> print(x*2)
6
>>> print(x**2) # 2次方
9
>>> print(x**3) # 3次方
27
>>> print(x/2) # 浮点数除法
1.5
>>> print(x//2) # 整数除法
1
>>> x+=1
>>> print(x)
4
>>> x*=2
>>> print(x)
8
>>> y = 2.5
>>> print(type(y))
<class 'float'>
>>> print(y,y+1,y*2,y**2)
2.5 3.5 5.0 6.25
布尔型:
python中有布尔类型boolean,以英文表示而非字符如&&、||等。布尔类型区分大小写,正确写法是True、False而非true、false。
>>> t = True
>>> f = False
>>> print(type(t))
<class 'bool'>
>>> print(t and f) # 与
False
>>> print(t or f) # 或
True
>>> print(not t) # 非
False
>>> print(t!=f)
True
Strings:
>>> hello = 'hello' # 入门第一步,hello world!
>>> world = "world"
>>> print(hello)
hello
>>> print(len(hello))
5
>>> hw = hello + ' ' + world
>>> print(hw)
hello world
>>> hw12 = '%s %s %d' % (hello,world,12)
>>> print(hw12)
hello world 12
>>> s = "hello"
>>> print(s.capitalize()) # 首字母大写
Hello
>>> print(s.upper()) # 全部大写
HELLO
>>> print("HELLO".lower()) # 全部小写
hello
>>> print(s.rjust(7)) # 占7位,右对齐
hello
>>> print(s.ljust(7)) # 占7位,左对齐
hello
>>> print(s.center(7)) # 占7位,中间对齐
hello
>>> print(s.replace('l','o')) # 替换
heooo
>>> print(' hello world '.strip()) # 去除首尾空白符
hello world
列表
Python含有几个内置的容器类型:列表、字典、集合和元组。
列表List能包含多种不同类型的元素。在Python中相当于数组,但它的大小可以改变。不同于元组的是,列表可动态增加,删除,更新。
列表基本操作
>>> xs = [3,1,2] # []定义列表
>>> print(xs,xs[2]) # 列表下标以0开始计数
[3, 1, 2] 2
>>> print(xs[-1]) # 负索引从列表的末尾开始计算
2
>>> print(xs[-2])
1
>>> xs[2] = 'foo'
>>> print(xs)
[3, 1, 'foo']
>>> xs.append('bar') # 添加元素
>>> print(xs)
[3, 1, 'foo', 'bar']
>>> x = xs.pop() # 删除元素
>>> print(x,xs)
bar [3, 1, 'foo']
切片Slicing
>>> nums = list(range(5))
>>> print(nums)
[0, 1, 2, 3, 4]
>>> print(nums[2:4]) # 不含末位!
[2, 3]
>>> print(nums[2:])
[2, 3, 4]
>>> print(nums[:2])
[0, 1]
>>> print(nums[:])
[0, 1, 2, 3, 4]
>>> print(nums[:-1]) # 下表-1对应元素为4
[0, 1, 2, 3]
>>> nums[2:4] = [8,9] # 替换
>>> print(nums)
[0, 1, 8, 9, 4]
列表循环
>>> animals = ['cat','dog','monkey']
>>> for animal in animals: # 循环
print(animal)
cat
dog
monkey
>>> for idx,animal in enumerate(animals): # 枚举循环
print('#%d: %s' % (idx + 1,animal))
#1: cat
#2: dog
#3: monkey
列表推导式List comprehensions
>>> nums = [0,1,2,3,4]
>>> squares = []
>>> for x in nums:
squares.append(x ** 2)
>>> print(squares)
[0, 1, 4, 9, 16]
>>> nums = [0,1,2,3,4]
>>> squares = [x ** 2 for x in nums]
>>> print(squares)
[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)
[0, 4, 16]
字典
字典是无序的,存储键值对数据。最外面用大括号,每一组用冒号连起来,然后各组用逗号隔开。
字典基本操作
>>> d = {'cat':'cute','dog':'furry'} # 定义字典
>>> print(d['cat']) # 输出cat对应的值
cute
>>> print('cat' in d) # 判断cat是否在字典里
True
>>> d['fish'] = 'wet' # 为字典添加新元素
>>> print(d['fish'])
wet
>>> print(d['monkey']) # monkey不在字典内
KeyError: 'monkey'
>>> print(d.get('monkey','N/A')) # 获取失败则输出缺省值'N/A'
N/A
>>> print(d.get('fish','N/A')) # 获取成功则输出相应值
wet
>>> del d['fish'] # 删除元素
>>> print(d.get('fish','N/A'))
N/A
字典循环
>>> d = {'person':2,'cat':4,'spider':8}
>>> for animal in d:
legs = d[animal]
print('A %s has %d legs' % (animal,legs))
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))
A person has 2 legs
A cat has 4 legs
A spider has 8 legs
字典推导式Dictionary comprehensions
>>> d = {'person':2,'cat':4,'spider':8}
>>> 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}
集合
集合是一个无序不重复元素集。
集合基本操作
>>> animals = {'cat','dog'} # 定义集合
>>> print('cat' in animals) # 判断cat是否在集合内
True
>>> print('fish' in animals) # 判断fish是否在集合内
False
>>> animals.add('fish') # 添加元素
>>> print('fish' in animals)
True
>>> print(len(animals))
3
>>> animals.add('cat') # cat在集合内,故不作改变
>>> print(len(animals))
3
>>> animals.remove('cat') # 删除元素
>>> print(len(animals))
2
集合循环,由于无序,所以不能使用for…in…方法进行循环。
>>> animals = {'cat','dog','fish'}
>>> for idx,animal in enumerate(animals):
print('#%d: %s' % (idx+1,animal))
#1: dog
#2: cat
#3: fish
集合推导式Set comprehensions
>>> from math import sqrt
>>> nums = {int(sqrt(x)) for x in range(30)}
>>> print(nums)
{0, 1, 2, 3, 4, 5}
元组
元组是一个(不可变的)有序的值列表。元组在许多方面与列表相似,最重要的区别之一是,元组可以用作字典中的键,也可以作为集合的元素,而列表则不能。
元组一旦定义其长度和内容都是固定的。一旦创建元组,则这个元组就不能被修改,即不能对元组进行更新、增加、删除操作。
元组基本操作
>>> d = {(x,x+1): x for x in range(10)} # 字典
>>> t = (5,6) # 元组
>>> print(type(t))
<class 'tuple'>
>>> print(d[t])
5
>>> print(d[(1,2)])
1
函数
>>> 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, %s!' % name.upper())
else:
print('Hello, %s' % name)
>>> hello('Bob')
Hello, Bob
>>> hello('Fred',loud = True)
HELLO, FRED!
类
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')
g.greet()
g.greet(loud=True)
# 运行结果:
# Hello, Fred
# HELLO, FRED!
---------------------
转载,仅作分享,侵删
作者:wangprince2017
原文:https://blog.csdn.net/u010608296/article/details/85342029
|
|