Python 学习(1)---基本知识整理

本文详细介绍了Python编程的基础知识,包括函数相关、容器使用、lambda匿名函数的使用等核心内容,以及Python中的容器如字典和集合的常用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python 是一门很灵活、很方便的语言。学起来很顺手,我们可以用它快捷的完成许多实际任务,下面是我学习python的过程中整理的基本知识点。

1 函数相关:

a) 函数嵌套及函数闭包:

# -*- coding:utf-8 -*-
# __author__ = 'Microcosm'
"""
函数闭包的测试
"""

print("-------------------函数闭包的测试-----------------------")
def funx(x):
    def funy(y):    # 引用外变量形成函数闭包
        return x*y
    return funy     # 返回函数

i = funx(8)
print type(i)

print i(5)
print funx(8)(5)

print("\n-------------嵌套函数引用外部变量的方式---------------------")
def fun1():
    x = [5]   # 当x为容器时,嵌套函数才能识别,否则嵌套函数中的x 只是一个未定义的局部变量
    def fun2():
    #   nonlocal x  # Python3 增加的关键字 与 global 对应
        x[0] *= x[0]
        return x[0]
    return fun2()

print fun1()

print("\n--------------函数收集参数-----------------------")
def test1(*parms):
    print "参数的个数为: ", len(parms)
    print "第二个参数为: ", parms[1]

test1(1,"a",2.24,3,-5,7,8)

print("\n--------------默认参数---------------------------")
def test2(expe=8, *parms):   # 这个版本的python 收集参数只能放在后面
    print "参数的个数为: ", len(parms),expe
    print "第二个参数为: ", parms[1]

test2(6,1,"a",2.24,3,-5,7,8)


print("\n-----------------函数返回多个值的方式---------------")
def test():
    return [1, 2, "a"]  # 返回一个列表
    #return 1,2,"小甲鱼"   # 返回一个元组,元组的标志是变量后面有逗号,而不是加小括号

a,b,c = test()
print a
print b
print c

b) 函数递归:

# -*- coding:utf-8 -*-
__author__ = 'Microcosm'

import sys

sys.setrecursionlimit(10000)   # 设置最大递归深度

print """
递归函数的几个应用
"""
print("---------------------求阶乘-----------------")
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

print "求阶乘的函数"
num = input('请输入一个整数: ')
result = factorial(num)
print "%d 的阶乘是: %d"  %(num, result)

print("---------------求斐波那契数列-----------------")
def Fib(n):
    if n < 0:
        print "输入有误!必须为正整数!"
        return -1
    elif n == 1 or n == 2:
        return 1
    else:
        return Fib(n-1)+Fib(n-2)

print "求斐波那契数列的函数"
num = input("请输入一个正整数:")
result = Fib(num)
print "第 %d 个斐波那契数为: %d" %(num, result)

print("------------------------汉诺塔问题-----------------------")
def move(x,z):
    print "从 %s 移动到 %s" % (x,z)

def hanuota(x,y,z,n):
    if n == 1:
        move(x,z)
    else:
        hanuota(x,z,y,n-1)  # 先将X上的n-1个盘子移动到Y上
        move(x,z)           # 再将X上的最后一个盘子移动到Z上
        hanuota(y,x,z,n-1)  # 然后将Y上的n-1个盘子移动到Z上

print "求汉诺塔问题"
num = input("请输入汉诺塔的层数: ")
hanuota("X", "Y", "Z", num)

c) lambda匿名函数的使用

# -*- coding: utf-8 -*-
__author__ = 'Microcosm'

print """
匿名函数:不需要定义
"""

print("----------------lambda表达式--------------------")
g = lambda x: 2*x + 1
print g(5)

f = lambda x, y: x+y
print f(3,4)

print("--------------有用的内置函数filter()------------------")
help(filter)  #  查看其使用方法
# filter(function or None, sequence)使用function过滤掉function(sequence)为假的值,留下为真的值
def odd(x):
    return x % 2

temp = filter(odd,range(10))  # 过滤掉偶数
print temp

print("-----------------结合lambda表达式使用-------------------")
temp = filter(lambda x:x%2, range(10))
print temp

print("-------------------有用的内置函数map()结合lambda表达式的使用--------------")
help(map)
# map(function ,sequence) 返回function(sequence)
temp = map(lambda x: 2 * x, range(10))
print temp

2 python中的容器使用

# -*- coding:utf-8 -*-
__author__ = 'Microcosm'

print """
python 的容器
"""

print("--------------------字典dict----------------------")
print "创建字典的方式:"
dict_empty = {}  # 空字典
print dict_empty
dict1 = {'LiNing':'everything is possible','Nike':'just do it','adidas':'nothing is impossible'}
print dict1
print dict1.keys()
dict2 = {1:"one",2:"two",3:"three",4:"four",5:"five"}
print dict2
dict3 = dict((('F',70),('i',105),('s',115),('h',104),('C',67)))
print dict3
dict4 = dict(a='programing change the world',b='hardworking to sucess')
print dict4
dict4['b'] = 'only hardworking can get a good chance'   # 改变键对应的值
print dict4
dict4['c'] = 'to be a genius'  # 添加进来了
print dict4

print("-----------------------字典常用的方法---------------------------")
dict5 = {}
dict5 = dict5.fromkeys(range(16),'good')
print dict5

for eachKey in dict5.keys():    # 取出键
    print eachKey
    print dict5[eachKey]

for eachVal in dict5.values():  # 取出值
    print eachVal

for eachItem in dict5.items():  # 取出项
    print eachItem

# get函数
print(dict5.get(17))  # 越界索引时返回None 比直接用下标索引好,dict5[17]会报错,影响用户体验

# clear函数
dict5.clear()  # 清空dict5   不要用dict5 = {} 这种方式不好,有时会出问题
print dict5

print "-----------------浅拷贝和赋值的区别----------------"
a = {1:'one',2:'two',3:'three'}
b = a.copy()
c = a
print a
print b
print c
# 查看它们的地址
print id(a)
print id(b)
print id(c)
# 浅拷贝也是一种拷贝,而赋值只是取了个别名指向同一片内存
c[4] = 'four'
print "c=", c
print "a=", a
print "b=", b

# pop 函数: 弹出一个键对应的值,同时字典中剔除掉这个项
print a.pop(2)

# popitem 函数
print c.popitem()  # 会随机弹出一个项

# setdefault 函数:设置一个新的项
a.setdefault(5,'five')
print a
a.setdefault(6)
print a

# update 函数:用一个字典去更新另一个字典的值
a.update({6:'six',7:'seven'})
print a

print("--------------------------集合set------------------------")
num = {}   # 字典类型
print type(num)
num = {1,2,3,4,5} # 集合类型
print type(num)
num2 = {1,2,3,4,5,4,3,0}  # 集合的唯一性
print num2

# 创建集合
set1 = set([1,2,3,4,5,1])
print set1

# 剔除列表重复性元素的方式
num3 = [1,2,3,4,5,2,3,1,0]
temp = []
for each in num3:
    if each not in temp:
        temp.append(each)
print temp

# 利用集合的唯一性
num3 = list(set(num3))
print num3

print("----------------------集合的常用方法--------------------")
set2 = {1,2,4,5,3}
print set2
#print set2[2]   # 集合中的元素是无序的,不能用下标索引

set2.add(6)
print set2

set2.remove(5)
print set2

# 不可变集合
set3 = frozenset([1,2,3,4,5,6,3,2])
print set3
#set3.add(7)    都是错误操作,不能被修改的集合
#set3.remove(3)


集合的内建方法表:


待续。。。。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值