Python盒子:模块、包和程序

命令行参数
test2.py
import sys
print('Program arguments:', sys.argv)
D:\MyPython>python test2.py tra la la
('Program arguments:', ['test2.py', 'tra', 'la', 'la'])
模块和import语句
weatherman.py
import report
description = report.get_description()
print("Today's weather:", description)

report.py

def get_description():from random import choice   #可以改成import random      random.choice(possibilities)possibilities = ['rain', 'snow','sleet','fog']return choice(possibilities)

D:\MyPython>python weatherman.py
("Today's weather:", 'snow')

使用别名导入模块
import report as wr
description = wr.get_description()
print("Today's weather:", description)

导入模块的一部分

from report import get_description as do_it
description = do_it()
print("Today's weather:", description)

模糊搜索路径

import sys
for place in sys.path:print(place)
D:\MyPython>python report.py
D:\MyPython
C:\WINDOWS\SYSTEM32\python27.zip
D:\Python27\DLLs
D:\Python27\lib
D:\Python27\lib\plat-win
D:\Python27\lib\lib-tk
D:\Python27
D:\Python27\lib\site-packages
主程序是MyPython/weather.py, 还需要在sources目录下添加一个文件:__init__.py,这个文件可以是空的,但是python需要它,以便把该目录作为一个包
from sources import daily,weekly
print("Daily forecast:", daily.forecast())
print("Weekly forecast:")
for number ,outlook in enumerate(weekly.forecast(),1):    #enumerate()拆分一个列表print(number, outlook)
模块1是MyPython/sources/daily.py:
def forecast():'fake daily forecast'return 'like yesterday'

模块2是MyPython/sources/weekly.py:
def forecast():return ['snow', 'more snow', 'sleet', 'freezing rain', 'fog','hail']

D:\MyPython>python weather.py

('Daily forecast:', 'like yesterday')
Weekly forecast:
(1, 'snow')
(2, 'more snow')
(3, 'sleet')
(4, 'freezing rain')
(5, 'fog')
(6, 'hail')

使用setdefault()和defaultdict()处理缺失的键
periodic_table = {'Hydrogen':1,'Helium':2}
carbon = periodic_table.setdefault('Carbon', 12)  #如果键不存在字典中,会被添加进去
print(carbon)
print(periodic_table)
helium = periodic_table.setdefault('Helium', 11)       #试图把一个不同的默认值赋给已经存在的键,不会改变原来的返回原来的值
print(helium)

D:\MyPython>python test2.py
12
{'Helium': 2, 'Hydrogen': 1, 'Carbon': 12}
2

函数defaultdict()的参数是一个函数,它返回赋给缺失键的值,可以使用int(),list()或者dict()返回默认空的值:0,空列表([]), 空字典({}),如果没有添加该函数参数,新键的初始值会被设置为None
#_*_ coding:utf_8_*_
from collections import defaultdict
periodic_table = defaultdict(int)      #按照int()调用,返回整数0
periodic_table['Hydrogen'] = 1
print(periodic_table['Lead'])
def no_idea():return 'Huh?'
bestiary = defaultdict(no_idea)
bestiary['A'] = 'Abominable'
bestiary['B'] = 'Basilisk'
print(bestiary['C'])
print(bestiary)

D:\MyPython>python test2.py
0
Huh?
defaultdict(<function no_idea at 0x034FACF0>, {'A': 'Abominable', 'C': 'Huh?', 'B': 'Basilisk'})
用lambda来定义你的默认值函数

>>> bestiary = defaultdict(lambda: 'Huh?')
>>> bestiary['E']
使用Counter()计数
# _*_ coding: utf-8_*_
from collections import Counter
breakfast = ['span', 'span', 'eggs', 'span']
breakfast_counter = Counter(breakfast)
print(breakfast_counter)
print(breakfast_counter.most_common())
#降序返回所有元素,或者给定一个数字,返回该数字前的元素
lunch = ['eggs','eggs', 'bacon']
lunch_counter = Counter(lunch)
print(lunch_counter)
#组合计数器的方法是使用 :+
print(breakfast_counter + lunch_counter)
#什么是早餐有,午餐没有的 :-
print(breakfast_counter - lunch_counter)
#什么是两者都有的: &
print(breakfast_counter & lunch_counter)
#一共吃了什么东西
print(breakfast_counter | lunch_counter)
D:\MyPython>python test2.py
Counter({'span': 3, 'eggs': 1})
[('span', 3), ('eggs', 1)]
Counter({'eggs': 2, 'bacon': 1})
Counter({'eggs': 3, 'span': 3, 'bacon': 1})
Counter({'span': 3})
Counter({'eggs': 1})
Counter({'span': 3, 'eggs': 2, 'bacon': 1})
使用有序字典OrderedDict()按键排序
# _*_ coding: utf-8_*_
from collections import OrderedDict
quotes = {'Moe': 'A wise', 'Larry': 'Ow!', 'Curly': 'Nyyk'}
for stooge in quotes:print(stooge)
quotes = OrderedDict([('Moe', 'A wise'), ('Larry', 'Ow!'), ('Curly', 'Nyyk')])
for stooge in quotes:print(stooge)
D:\MyPython>python test2.py
Larry
Curly
Moe
Moe
Larry
Curly
双端队列:栈 + 队列
判断是否为回文
# _*_ coding: utf-8_*_
def palindrome(word):from collections import dequedq = deque(word)while len(dq) > 1:if dq.popleft() != dq.pop():   #popleft()去掉最左边的项并返回,pop()去掉最右边的并返回return Falsereturn True
print(palindrome('a'))

D:\MyPython>python test2.py
True
python没有对字符串进行反转的函数reverse(),但可以利用反向切片

def palindrome(word):return word == word[::-1]
print(palindrome('radar'))

使用itertools迭代代码结构

# _*_ coding: utf-8_*_
import itertools
for item in itertools.chain([1,2],['a', 'b']):print(item)
D:\MyPython>python test2.py
1
2
a
b
cycle()在它的参数之间循环的无限迭代器
import itertools
for item in itertools.cycle([1,2]):print(item)

accumulate()计算累积的值,默认的话,它计算的是累加和:


>>> import itertools
>>> for item in itertools.accumulate([1,2,3,4]):
...     print(item)
...
1
3
6
10
>>>
>>> def multiply(a, b):
...     return a * b
...
>>> for item in itertools.accumulate([1,2,3,4],multiply):
...     print(item)
...
1
2
6
24

使用pprint()可以尽量排列输出元素从而增强可读性:

>>> from pprint import pprint
>>> from collections import OrderedDict
>>> quotes  = OrderedDict([('moe','df'),('larry','ow'),('curly','Nyuk')])
>>> print(quotes)
OrderedDict([('moe', 'df'), ('larry', 'ow'), ('curly', 'Nyuk')])
>>> pprint(quotes)
OrderedDict([('moe', 'df'), ('larry', 'ow'), ('curly', 'Nyuk')])
>>>

本文是我在学习了丁嘉瑞的《Python语言及其应用》所做的笔记,只用于学习。

Python盒子:模块、包和程序相关推荐

  1. Python | 使用时间模块编写倒计时程序

    文章目录 一,使用Python中的时间模块编写一个简易的倒计时程序 1.程序代码 2.运行结果 一,使用Python中的时间模块编写一个简易的倒计时程序 1.程序代码 ""&quo ...

  2. Python module模块 包 __name__

    模块:一个.py文件就称为一个模块(module) module的好处: •提高代码的可维护性,一个module编写完成,就可以被其它地方引用,不必重复编写,注意模块名应避免与python内置库重名 ...

  3. Python导入模块(包)的两种方式 TypeError: 'module' object is not callable

    Python编程时明明在开始处import了相关包,但是调用函数时就报错如下: TypeError: 'module' object is not callable Python中有两种导入包(模块, ...

  4. python 异常 模块 包

    #什么是异常 当Python检测到一个错误时,解释器就无法继续执行了,反而出现了一些错误的提示,这就是所谓的"异常" #捕获异常 使用try:...except:...来捕获异常, ...

  5. python random模块点餐程序_python之random模块

    random模块 用于生成随机浮点数.整数.字符串和随机抽取元素 方法: random()  生成一个随机浮点数,范围在0.0~1.0之间 uniform(上限,下限)  在设置的范围内,随机生成一个 ...

  6. Python 模块/包的导入以及 import 的用法总结

    Python 模块/包的导入以及 import 的用法总结 一.模块/包 1. 前言 一个以 .py 为后缀的 Python 文件就是一个模块. 包是一个文件夹或一个目录. 每个包都有一个全局定义的配 ...

  7. python module是干什么的_如何最简单、通俗地理解Python的模块?

    目录: 一.笔记 二.笔记目录 一.笔记 1) 模块 ① Python模块(Module),是一个Python文件,以.py结尾,包含了Python语句和Python对象定义,模块让你能够有逻辑地组织 ...

  8. python安装盒怎么打开_Python学习笔记(六)Python盒子:模块,包和程序

    关于独立的程序: 我们可以将编写的代码放到一个文本里,并将文件名命名为xxx.py的形式.如果想要运行程序,直接在终端或者命令终端输入 python xxx.py. 命令行参数 我们编写文件test. ...

  9. python cv2模块安装_Python运行脚本前,自动安装需要的模块包

    在服务器上部署Python程序时,往往需要先安装很多需要的模块包.如果一个一个安装就会出现忘记的情况.或者新增加某个新的模块时,也可能会忘记安装. 这里先讲一下怎么通过Python程序自动安装. 以下 ...

最新文章

  1. llvm常见问题 (FAQ)
  2. 隐藏在程序旮旯中的“安全问题”
  3. lepus mysql 复制监控_sql_mode=ONLY_FULL_GROUP_BY 导致lepus监控mysql5.7报错
  4. 三维离散点包络 matlab,求大神指点绘制空间内散点图的包络面,,,散点程序如下...
  5. java高并发(八)不可变对象
  6. java跨函数跳转_VS code 函数无法跨文件跳转到定义
  7. 百度SEO EBCMS(易贝管理系统) v1.2.0
  8. 惠普战66拆机加固态_惠普战66测评:想要提高办公效率,惠普是你的品质之选...
  9. atitit attilax的新目标 未来学家.docx
  10. 飞思卡尔 智能车(山大 Router) 核心源码
  11. Swarm(bzz)软启动版本v.0.0-rc2
  12. 读书百客:《宴清都·初春》赏析
  13. 第三课:创建BootRom引导镜像
  14. Arcmap制图调色
  15. Win_XP_SP3系统下成功安装WinccV6.0_SP3a 经验分享
  16. 使用poi导出excel
  17. Google 新系统 Fuchsia 概览和浅析
  18. 手写JavaScript
  19. 用 MAUI 在Windows 和 Linux 绘制 PPT 图表
  20. C语言学习入门(一)

热门文章

  1. 移动端H5-音视频资源优化方案实战方案推荐
  2. 计算机的教学内容相对抽象,职高计算机教育特殊性研究 石瑛
  3. Python 从后往前每隔三个数字加一个逗号的方法
  4. onscroll 事件和onScrollCapture事件
  5. STM32CudeMX使用步骤
  6. HackRF-AIS信号的采集与解调
  7. python numba cuda_Numba:基于CUDA加速的高性能Python
  8. termux之手机青龙
  9. crypto-js报UglifyJs错误
  10. 软件R的安装和使用(视窗电脑)