Python3 知识总结 基础篇代码

最新需要写个小工具,读取Excel数据。边学习了一下python3 基础知识总结如下,都是可以执行的代码。
参考资料 廖雪峰大神 python3教程

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
print(100 * 100)

#name = input('please enter your name: ')
#print('hello,', name)

#file = input()
#print('d ww= ', file)



print('''line1
... line2
... line3''')

# 占位符	替换内容
# %d	整数
# %f	浮点数
# %s	字符串
# %x	十六进制整数


str1 = 'Age: %s. Gender: %s' % (25, True)
print(str1)
str1 = 'growth rate: %d %%' % 7
print(str1)
str1 = 'Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)
print(str1)


classmates = ['Michael', 'Bob', 'Tracy']
len(classmates)
print(len(classmates))
# 如果要取最后一个元素,除了计算索引位置外,还可以用-1做索引,直接获取最后一个元素:
print(classmates[-1])
# list是一个可变的有序表,所以,可以往list中追加元素到末尾:
classmates.append('Adam')
print(classmates)
# 元素插入到指定的位置,比如索引号为1的位置: 下标从0开始
classmates.insert(1, 'Jack')
print(classmates)

# 删除list末尾的元素,用pop()方法:
classmates.pop()
print(classmates)
# 删除指定位置的元素,用pop(i)方法,其中i是索引位置:
classmates.pop(0)
print(classmates)
classmates.pop(-1)
print(classmates)

# list里面的元素的数据类型也可以不同
p = ['asp', 'php']
s = ['python', 'java', p, 'scheme']
print(len(s))
L = []
len(L)
print(len(L))


age = 3
if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
else:
    print('kid')

names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

    sum = 0
    for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
        sum = sum + x
    print(sum)

    # 如果要计算1 - 100
    # 的整数之和,从1写到100有点困难,幸好Python提供一个range()
    # 函数,可以生成一个整数序列,再通过list()
    # 函数可以转换为list。比如range(5)
    # 生成的序列是从0开始小于5的整数:
print(list(range(5)))
sum = 0
for x in range(101):
    sum = sum + x
print(sum)

# 字典

d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d)

list1 = [1,2,3,4,]
list2 = [2,1,34]
dic = {'qwe':list1,'asd':list2}
print(dic)

dic['zxc'] = list1
if dic.get('zxc'):
    dic['zxc'].append(55)
    print(dic['zxc'])


print(dic)


# 空函数
def nop():
    pass

def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x >= 0:
        return x
    else:
        return -x

    import math

    def move(x, y, step, angle=0):
        nx = x + step * math.cos(angle)
        ny = y - step * math.sin(angle)
        return nx, ny



from openpyxl import Workbook
wb = Workbook()

# grab the active worksheet
ws = wb.active

# Data can be assigned directly to cells
ws['A1'] = 42

# Rows can also be appended
ws.append([1, 2, 3])

# Python types will automatically be converted
import datetime
ws['A2'] = '223222'

# Save the file
wb.save("sample.xlsx")

# 类型转换
print("类型转换 ===  ")
print(int('123'))
print(int(12.3))
print(str(123.4))
print(float('12.34'))
print(bool(1))
print(bool(0))

# 空函数 如果想定义一个什么事也不做的空函数,可以用pass语句:

def nop():
    pass

# 递归函数
def fact1(n):
    if n==1:
        return 1
    return n * fact1(n - 1)



print(fact1(100))
# 优点 :
# 是定义简单,逻辑清晰。理论上,所有的递归函数都可以写成循环的方式,但循环的逻辑不如递归清晰。
# 缺点 :
# 使用递归函数需要注意防止栈溢出。在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,
# 栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。

# 尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。
# 这样,编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会出现栈溢出的情况。
def fact(n):
    return fact_iter(n, 1)

def fact_iter(num, product):
    if num == 1:
        return product
    return fact_iter(num - 1, num * product)

print(fact(100))

# 切片
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
# L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。
# L[:3]  如果第一个索引是0,还可以省略:
# L[-1]取倒数第一个元素,那么它同样支持倒数切片,
# L[n:m]
print(L[0:3])
print(L[2:3])

L = list(range(100))
# 后10个数:
print(L[-10:])
# 前10个数,每两个取一个:
print(L[:10:2])
# 所有数,每5个取一个:
print(L[::5])
# 甚至什么都不写,只写[:]就可以原样复制一个list:
print( L[:])
# tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple:
print((0, 1, 2, 3, 4, 5)[:3])
# 字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串:

print('ABCDEFG'[:3])


# 迭代器

for i, value in enumerate(['A', 'B', 'C']):
    print(i, value)

# 列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。
L = [x * x for x in range(1, 11)]
print(L)


import os # 导入os模块,模块的概念后面讲到
F = [d for d in os.listdir()]

# 生成器
# 通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。
# 而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
#
# 所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,
# 从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
#
# 要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:

L = [x * x for x in range(10)]
g = (x * x for x in range(10))
print(next(g))
for i in g:
    pass

 # 著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:
    #
    # 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
    #
    # 斐波拉契数列用列表生成式写不出来,但是,用函数把它打印出来却很容易:
print('斐波拉契数列=====')
FIB = []
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        FIB.append(b)
        a, b = b, a + b
        n = n + 1
    return 'done'

fib(10)
print(FIB)


print(u"高阶函数 ===== ")
# 高阶函数
x = abs(-10)
f = abs
# 传入函数
def add(x, y, f):
    return f(x) + f(y)

# map/reduce

# map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
def f(x):
    return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])

print(list(r))

print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))

# reduce
from  functools import  reduce
def AddReduce(x,y):
    return  x+y
print(reduce(AddReduce,[1, 3, 5, 7, 9]))
print(reduce(AddReduce, [1, 3, 5, 7, 9]))
# 如果要把序列[1, 3, 5, 7, 9]变换成整数13579,reduce就可以派上用场:
def fn(x, y):
    return x * 10 + y

print(reduce(fn,[1, 3, 5, 7, 9]))

# 字符串转化成 数字

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def str2int(s):
    def fn(x, y):
        return x * 10 + y
    def char2num(s):
        return DIGITS[s]
    return reduce(fn, map(char2num, s))

print(str2int('12345'))

# filter()函数用于过滤序列

def is_odd(n):
    return n % 2 == 1

print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))

# 把一个序列中的空字符串删掉
def not_empty(s):
    return s and s.strip()

print(list(filter(not_empty, ['A', '', 'B', None, 'C', '  '])))

# 排序算法
LS = sorted([36, 5, -12, 9, -21], key=abs)

print(LS)


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值