零基础入门学python 零基础入门学python课后题

144
作者 壹课学堂 米粒妈咪课堂  ← 点击红色字,关注公众号
2020-10-14 21:54 字数 3799 阅读 1087评论 0
从入门到进阶,轻松学Python!

  零基础入门学python 零基础入门学python课后题

  米粒妈咪网小编为你分享零基础入门学python之零基础入门学python课后题

  零基础入门学python课后题1,使用getopt。getopt()优化bai当前的功能函数:

  [html]

  #!/usr/bin/python

  # -*- coding: utf-8 -*-

  #coding=utf-8

  import os,sys

  import getopt

  print sys.argv

  CDROW='/home/zhouqian/test'

  def cdWalker(CDROW,cdfile):

  result=[]

  for root,dirs,files in os.walk(CDROW):

  result.append("%s %s %s" %(root,dirs,files))

  print root

  open(cdfile,'w').write('\n'.join(result))

  def usage():

  print '''pycdc 使用方式du:

  python cdays-3-exercise-1.py -d cdc -k 中国火

  #检索cdc中有没有zhi中国火字样的目录,

  '''

  try:

  opts,args=getopt.getopt(sys.argv[1:],'hd:e:k:')

  except getopt.GetoptError:

  usage()

  sys.exit()

  if len(opts)==0:

  usage()

  sys.exit()

  c_path=''

  name=''

  for opt,arg in opts:

  if opt in('-h','--help'):

  usage()

  sys.exit()

  elif opt=='-e':

  if os.path.exists(arg):#判断目标路径dao是否存在

  # cdWalker(CDROW,arg)

  print "记录光盘的位置是 %s" %arg

  else:

  print "不存在这样的目录"

  elif opt=='-d':

  c_path=arg

  print c_path

  cdWalker(CDROW,c_path)

  elif opt=='-k':

  if not c_path:

  usage()

  sys.exit()

  else:

  name=arg

  for root,dirs,files in os.walk(c_path):

  if root=='%s' %name:

  print '您要找的文件在%s' %dirs

  这是第一个零基础入门学python课后题,大概做了2个小时吧,各种纠结啊,后面两个正在做。中间遇到的问题总结:

  函式的利用,os.path.walk,python字符集,getopt模块的使用学习,os.path.exists()的利用,列表的对应关系等等

  零基础入门学python课后题习题2 :关键词-----》序列号问题:

  [html]

  #!/usr/bin/python

  #coding=utf-8

  import sys

  def collect(file):

  result={}

  for line in file.readlines():

  left,right=line.split()

  if result.has_key(right):

  result[right].append(left)

  else:

  result[right]=[left]

  return result

  if __name__=="__main__":

  print sys.argv

  if len(sys.argv)==1:

  print 'usage:\tpython value_keys.py test.txt'

  else:

  result=collect(open(sys.argv[1],'r'))

  for (right,left) in result.items():

  print "%d %s => %s" %(len(left),right,left)

  零基础入门学python课后题结果显示:

  [html]

  root@zhou:/home/zhouqian/python# py value_keys.py test.txt

  ssss

  2 key3 => ['6', '33']

  3 key2 => ['1', '2', '45']

  3 key1 => ['4', '5', '13']

  零基础入门学python课后题遇到的问题总结:

  split的用法:line.split()就是分开出左右两边的值,在默认的情况下是以一个空格或者多个空格为分割符的,

  has_key()的用法:是查看字典数据类型中有没有这么一个关键字。上面可知result={}是初始化了一个字典的数据类型。

  字典的一些用法:怎么定义,怎么赋值:result[right]=[left]或者result[right]=left,遍历字典中所用

  项,result.items(),遍历字典的key值:result.keys(),遍历字典的value值:result.values()

  [html]

  >>> dict={'chen':25,'zhou':24,'xiao':35}

  >>> dict.values()

  [25, 35, 24]

  >>> dict.keys()

  ['chen', 'xiao', 'zhou']

  >>> dict.items()

  [('chen', 25), ('xiao', 35), ('zhou', 24)]

  更多关于python编程入门 python编程入门知识 相关信息,请关注米粒妈咪课堂公共号。


通用技能      米粒妈咪在线课程