python—函数(返回整型最大/最小值、返回字符串最长的串、)
习题:
1.定义一个方法 func,该func可以引入任意多的整型参数,结果返回其中最大与最小的值。
使用元组的求解最大值/最小值的函数(http://www.yiibai.com/python/tuple_max.html),使用函数返回多个值(http://www.cnblogs.com/xiaoit/p/4046533.html)
元组内置函数
Python元组包含了以下内置函数
1、cmp(tuple1, tuple2):比较两个元组元素。
2、len(tuple):计算元组元素个数。
3、max(tuple):返回元组中元素最大值。
4、min(tuple):返回元组中元素最小值。
5、tuple(seq):将列表转换为元组。
root@kali:~/python/laowangpy/function# cat 1funcmaxmin.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
def funtuple(*num):
return max(num),min(num)
print funtuple(1,4,5,6,2,3,57,8)
print funtuple(33,67,8,9,12,36,44,2,3)
root@kali:~/python/laowangpy/function# python 1funcmaxmin.py
(57, 1)
(67, 2)
root@kali:~/python/laowangpy/function#
2.定义一个方法func,该func可以引入任意多的字符串参数,结果返回(长度)最长的字符串。
两种解决方式:
方法一:使用list列表的lambda,sorted排序一句话解决(https://zhidao.baidu.com/question/268619689814821485.html)
root@kali:~/python/laowangpy/function# cat 2funcmaxchar.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
list = []
def lenchartuple(*char):
list.append(char)
print list
return sorted(list[0],key=lambda x: len(x))[-1]#使用sored对列表从小到大排序,取最后一个最大元素
#print lenchartuple("qwssd","werewfdfdsfdsf","ac","xwbfg")
print lenchartuple("cdf","fvfgregr","retsdvreg","rgerfdbfgnhgh")
root@kali:~/python/laowangpy/function# python 2funcmaxchar.py
[('cdf', 'fvfgregr', 'retsdvreg', 'rgerfdbfgnhgh')]
rgerfdbfgnhgh
root@kali:~/python/laowangpy/function#
方法二:使用list列表转换成字典、字典的值使用max/min和lanbda(http://www.cnblogs.com/harvey888/p/6006202.html)
参考
Python中获取字典中最值对应的键
利用min(dict, key=dict.get)
>>> d = {1:1, 2:0, 3:2}
{1: 1, 2: 0, 3: 2}
>>> min(d, key=d.get)
2
利用lambda函数
>>> min(d.items(), key=lambda x: x[1])
(2, 0)
>>> min(d, key=lambda x: d[x])
2
root@kali:~/python/laowangpy/function# cat 2funcmaxchar.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
dic = {}
list = []
def lenchartuple(*char):
i = 0
list.append(char)
print list
#return sorted(list[0],key=lambda x: len(x))[-1]
while list[0][i] != "":
dic[list[0][i]] = len(list[0][i])
i = i + 1
#利用min(dict, key=dict.get)
return max(dic, key=dic.get)
#利用lambda函数
#return max(dic.items(), key=lambda x: x[1])
#return max(dic, key=lambda x: dic[x])
#print lenchartuple("qwssd","werewfdfdsfdsf","ac","xwbfg")
print lenchartuple("cdf","fvfgregr","retsdvreg","rgerfdbfgnhgh","")
root@kali:~/python/laowangpy/function# python 2funcmaxchar.py
[('cdf', 'fvfgregr', 'retsdvreg', 'rgerfdbfgnhgh', '')]
rgerfdbfgnhgh
root@kali:~/python/laowangpy/function#
3.定义一个方法get_doc(module),module参数为该脚本中导入或定义的模块对象,该函数返回module的帮助文档。
方法一:
例 print get_doc(urllib),则会输出urllib这个模块的帮助文档。(http://www.cnblogs.com/alan-babyblog/archive/2016/02/29/5227869.html)
使用动态导入import()模块功能,加载随时需要查询的模块
root@kali:~/python/laowangpy/function# cat 3gethelpmodule.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
def gethelpmod(*char):
c = char[0]
print c#打印要输出的模块名称
helpmod = __import__(c)#使用动态导入__import__()模块功能,加载随时需要查询的模块
return help(helpmod)
print gethelpmod("urllib")
root@kali:~/python/laowangpy/function# python 3gethelpmodule.py
urllib
None
root@kali:~/python/laowangpy/function#
dir()查看模块属性
# 方式:使用__import__()导入模块
# 导入指定模块,导入时会执行全局方法。
ip_module = __import__(imp_module)
# dir()查看模块属性
print(dir(ip_module))
root@kali:~/python/laowangpy/function# cat 3gethelpmodule.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
def gethelpmod(*char):
c = char[0]
print c#打印要输出的模块名称
helpmod = __import__(c)#使用动态导入__import__()模块功能,加载随时需要查询的模块
return help(helpmod)
print dir(gethelpmod("urllib"))
root@kali:~/python/laowangpy/function#
root@kali:~/python/laowangpy/function# python 3gethelpmodule.py
urllib
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
root@kali:~/python/laowangpy/function#
方法二:
root@kali:~/python/laowangpy/function# cat 3gethelpmodule2.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
import os
def gethelpmod(module):
a = 'pydoc %s' % module#使用pydoc可以直接读取任意模块的帮助文档,格式为pydoc urllib
m = os.popen(a).read()
return m
print gethelpmod("urllib")
root@kali:~/python/laowangpy/function# python 3gethelpmodule2.py
Help on module urllib:
NAME
urllib - Open an arbitrary URL.
FILE
/usr/lib/python2.7/urllib.py
MODULE DOCS
http://docs.python.org/library/urllib
DESCRIPTION
See the following document for more info on URLs:
"Names and Addresses, URIs, URLs, URNs, URCs", at
http://www.w3.org/pub/WWW/Addressing/Overview.html
............
............
............
............
pydoc 可以直接运行。格式为pydoc xxxx(模块名)
root@kali:~/python/laowangpy/function# pydoc
pydoc - the Python documentation tool
pydoc <name> ...
Show text documentation on something. <name> may be the name of a
Python keyword, topic, function, module, or package, or a dotted
reference to a class or function within a module or module in a
package. If <name> contains a '/', it is used as the path to a
Python source file to document. If name is 'keywords', 'topics',
or 'modules', a listing of these things is displayed.
pydoc -k <keyword>
Search for a keyword in the synopsis lines of all available modules.
pydoc -p <port>
Start an HTTP server on the given port on the local machine.
pydoc -g
Pop up a graphical interface for finding and serving documentation.
pydoc -w <name> ...
Write out the HTML documentation for a module to a file in the current
directory. If <name> contains a '/', it is treated as a filename; if
it names a directory, documentation is written for all the contents.
root@kali:~/python/laowangpy/function# pydoc urllib
root@kali:~/python/laowangpy/function#
4.定义一个方法get_text(f),f参数为任意一个文件的磁盘路径,该函数返回f文件的内容。(参考http://www.jb51.net/article/48001.htm)
#linux的目录读取
root@kali:~/python/laowangpy/function# cat 4pathwin.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
import sys
import os
def gettext(*path):
print path[0]
return os.listdir(path[0])
print gettext("/root/python/laowangpy/function/")
root@kali:~/python/laowangpy/function# python 4pathwin.py
/root/python/laowangpy/function/
['funvar2.py', 'fuc_name_1.py', '4pathwin.py', '2funcmaxchar.py', '3gethelpmodule.py', 'fuc_add.py', 'funvar1.py', '.4pathwin.py.swp', '1funcmaxmin.py', 'funvar3.py']
root@kali:~/python/laowangpy/function#
#windows的目录读取
#!/usr/bin/python
# --*-- coding:utf-8 --*--
import sys
import os
def gettext(*path):
print path[0]
return os.listdir(path[0])
print gettext("D:/BaiduNetdiskDownload/")
C:\Python27>python 4pathwin.py
D:/BaiduNetdiskDownload/
['.accelerate', '002-\xd0\xa1\xbc\xd7\xd3\xe3\xa1\xaa\xa1\xaaPython', '005-\xc1\xb6\xca\xfdPYTHON', '010\xc0\xcf\xc4\xd0\xba\xa2 python\xbf\xce\xb3\xcc', 'python', 'python33', 'Python3\xb3\xcc\xd0\xf2\xbf\xaa\xb7\xa2\xd6\xb8\xc4\xcf.\xb5\xda\xb6\xfe\xb0\xe6(\xb4\xf8\xca\xe9\xc7\xa9)', 'Python\xbf\xaa\xb7\xa2\xbc\xbc\xca\xf5\xcf\xea\xbd\xe2.pdf', '\xc0\xcf\xcd\xf5Python', '\xc0\xcf\xc4\xd0\xba\xa2python\xd7\xd4\xb6\xaf\xbb\xaf\xd4\xcb\xce\xac\xca\xd3\xc6\xb5\xbd\xcc\xb3\xcc\xa3\xa8\xc8\xab9\xbc\xaf\xa3\xa9']
C:\Python27>
5.定义一个方法get_dir(folder),folder参数为任意一个文件夹,该函数返回folder文件夹的文件列表。提示(可以了解python的glob模块)
参考(http://blog.csdn.net/csapr1987/article/details/7469769)
root@kali:~/python/laowangpy/function# python 5getdirfolder.py
['/root/python/laowangpy/function/funvar2.py', '/root/python/laowangpy/function/fuc_name_1.py', '/root/python/laowangpy/function/4pathwin.py', '/root/python/laowangpy/function/2funcmaxchar.py', '/root/python/laowangpy/function/3gethelpmodule.py', '/root/python/laowangpy/function/fuc_add.py', '/root/python/laowangpy/function/5getdirfolder.py', '/root/python/laowangpy/function/funvar1.py', '/root/python/laowangpy/function/1funcmaxmin.py', '/root/python/laowangpy/function/funvar3.py', '/root/python/laowangpy/datadig/5whichhours.py', '/root/python/laowangpy/datadig/8sourcefre.py', '/root/python/laowangpy/datadig/2username.py', '/root/python/laowangpy/datadig/12lenmicroblog.py', '/root/python/laowangpy/datadig/9forwardurl.py', '/root/python/laowangpy/datadig/sometime.py', '/root/python/laowangpy/datadig/4adddaysdata.py', '/root/python/laowangpy/datadig/1userid.py', '/root/python/laowangpy/datadig/11funuidmaxweb.py', '/root/python/laowangpy/datadig/221printuid.py', '/root/python/laowangpy/datadig/720121103fre.py', '/root/python/laowangpy/datadig/10uidweibo.py', '/root/python/laowangpy/datadig/6onedaydict.py', '/root/python/laowangpy/datadig/3numberof201211.py']
===========================================
['../searchzimu.py', '../dictserch.py', '../test_def_info_list.py', '../sortzimu.py', '../geshihua.py', '../sortzimu2.py', '../hello.py', '../sortdaxiao.py', '../def1.py', '../test_def_info.py', '../idsearch.py', '../nocount.py', '../beiscount.py', '../print_cont.py', '../searchzimu2.py', '../print_test.py', '../list_demo.py', '../print1.py', '../withtest.py', '../zimuchange.py', '../test_uncode.py']
root@kali:~/python/laowangpy/function# cat 5getdirfolder.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
import sys
import os
import glob
import re
print glob.glob(r"/root/python/laowangpy/*/*.py")
print "==========================================="
print glob.glob(r'../*.py')
root@kali:~/python/laowangpy/function#
root@kali:~/python/laowangpy# ls
a.txt function list_demo.py print_cont.py pytest2_env sortzimu2.py test_def_info.py
beiscount.py geshihua.py logid.txt print_test.py result.txt sortzimu.py test_uncode.py
datadig hello.py memid.txt print_test.txt searchzimu2.py test1.txt withtest.py
def1.py idsearch.py nocount.py _project searchzimu.py test2.txt zimuchange.py
dictserch.py id.txt print1.py pytest1_env sortdaxiao.py test_def_info_list.py
root@kali:~/python/laowangpy# pwd
/root/python/laowangpy
root@kali:~/python/laowangpy#
glob模块是最简单的模块之一,内容非常少。用它可以查找符合特定规则的文件路径名。跟使用windows下的文件搜索差不多。查找文件只用到三个匹配符:"*", "?", "[]"。"*"匹配0个或多个字符;"?"匹配单个字符;"[]"匹配指定范围内的字符,如:[0-9]匹配数字。
glob.glob
返回所有匹配的文件路径列表。它只有一个参数pathname,定义了文件路径匹配规则,这里可以是绝对路径,也可以是相对路径。下面是使用glob.glob的例子:
import glob
#获取指定目录下的所有图片
print glob.glob(r"E:\Picture\*\*.jpg")
#获取上级目录的所有.py文件
print glob.glob(r'../*.py') #相对路径
import glob #获取指定目录下的所有图片 print glob.glob(r"E:\Picture\*\*.jpg") #获取上级目录的所有.py文件 print glob.glob(r'../*.py') #相对路径
glob.iglob
获取一个可编历对象,使用它可以逐个获取匹配的文件路径名。与glob.glob()的区别是:glob.glob同时获取所有的匹配路径,而 glob.iglob一次只获取一个匹配路径。这有点类似于.NET中操作数据库用到的DataSet与DataReader。下面是一个简单的例子:
import glob
#父目录中的.py文件
f = glob.iglob(r'../*.py')
print f #<generator object iglob at 0x00B9FF80>
for py in f:
print py
import glob #父目录中的.py文件 f = glob.iglob(r'../*.py') print f #<generator object iglob at 0x00B9FF80> for py in f: print py
实际脚本运行情况:
root@kali:~/python/laowangpy/function# python 5getdirfolder.py
===========================================
<generator object iglob at 0xb74f2694>
../../function1.py
../../userinput.py
../../tab.py
../../dict_empleer.py
../../test2.py
../../fileinputreadfile.py
../../fileinputbak.py
../../manage_query.py
../../scanhostport.py
../../listshopingver3.py
../../listshoppingver4.py
../../scan1.py
../../listshopping.py
../../listshopingver2.py
../../fileseekstart.py
../../fileseekblank.py
../../test.py
../../fileseek.py
root@kali:~/python/laowangpy/function# cat 5getdirfolder.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
import sys
import os
import glob
import re
folder = glob.iglob(r'../../*.py')
print folder
for py in folder:
print py
root@kali:~/python/laowangpy/function#
root@kali:~/python# ls
atm fileinputbak.py listshopping.py oldtext.txt socket
atmnew fileinputreadfile.py listshoppingver4.py paramiko tab.py
atmnewaccount.py_2017-06-13_234645.tgz fileseekblank.py log pickle tab.pyc
atmnewatmnew_2017-06-13_235934.tgz fileseek.py manage_query.py polemeeor.txt test2.py
contact_list.txt fileseekstart.py mod _project test2.txt
contact_list.txt.bak function1.py modfuc scan1.py test.py
csvt01 laowangpy multiprocess scanhostport.py test.txt
csvtpy listshopingver2.py mysql shoppinglist.txt userinput.py
dict_empleer.py listshopingver3.py newtext.txt snmp xwbtest.txt
root@kali:~/python# pwd
/root/python
root@kali:~/python#