十分钟学会python

1.raw_input的使用

从键盘读取信息,返回字符串

例:

hrs = raw_input("Enter Hours:")
pay=raw_input("Enter Pay:")
print float(hrs)*float(pay)

2.try: except:  类似c中的try throw catch

3.strings

几个有用的string处理函数:

1)len(string)某字符串的长度

2)string.startswith('str')某字符串是否以str开头

3)lstrip('x') rstrip('x')  strip('x')删除字符串左面 右面 全部的x

4)string.find('a','b')从b开始寻找第一个a所在的位置(python中的计数方式从0开始)

5) string.split('x') 以x分割字符

注意:string[n:m]不包括第m个元素

4.python关于文件的读取

示例程序 找出文件中

X-DSPAM-Confidence:    0.8475    这样的行,并计算平均值

fname = raw_input("Enter file name: ")  
fh = open(fname)                                                                  #fh为文件的句柄
total=0
count=0
for line in fh:
  if not line.startswith("X-DSPAM-Confidence:") :

    continue
  h=line.find(':')
  i=line.find('/n',h)
  num=line[h+1:i]
  num=float(num)
  total=total+num
  count=count+1
average=total/count
print "Average spam confidence:",average

5.list

ls=list()构建一个空的list

ls.append()向ls中添加一个元素

list.sort() 排序

max(list) min(list)  sum len...

示例:

Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

代码:

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line.strip('\n')
    words=line.split()
    for word in words:
        if word not in lst:
            lst.append(word)
            lst.sort()
print lst

6.dictionary

字典是使用哈希存储的一种数据结构,所以输出字典是随机的 这点与list不同

字典中每个key对应一个value

例:

>>>dic={'tom':1,'Sam':2,'Peter':3}

>>>print list(dic)

['Tom','Sam','Peter']

>>>print dic.keys()

['Tom','Sam','Peter']

>>>print dic.values()

[1,2,3]

>>>print dic.items()

[('tom',1),(),()]

dictionary有个一非常有意思的函数get()

dic[a]=dic.get(a,0)+1

如果字典中没有a的话将其加入,如果有a的话将其+1

7.sort()与sorted()的比较

sort方法仅被定义在list中,而sorted对所有可迭代序列都有效

只需要调用sorted()方法。它返回一个新的list,新的list的元素基于小于运算符(__lt__)来排序。

你也可以使用list.sort()方法来排序,此时list本身将被修改。通常此方法不如sorted()方便,但是如果你不需要保留原来的list,此方法将更有效。

8.tuples

tuples和list类似,但是tuples一但确定了就不能更改

>>>tup=(1,2,3)注意这里是(),而list的初始化用的是[]。

例:Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.

From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008

Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.

代码:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
dic=dict()
for line in handle:
     if not line.startswith('From '):
       continue
  words=line.split()
  word=words[5]
  time=word.split(':')
  hour=time[0]
  dic[hour]=dic.get(hour,0)+1
tupl=sorted(dic.items())
for hour,times in sorted(tupl):
  print hour,times

8.c={'a':10,'b':1,'c':5}

print sorted([(v,k)] for k,v in c.items())

链表推导式

链表推导式提供了一个创建链表的简单途径,无需使用 map(), filter() 以及 lambda。返回链表的定义通常
要比创建这些链表更清晰。每一个链表推导式包括在一个for语句之后的表达式,零或多个for或if语句。返回
值是由for或if子句之后的表达式得到的元素组成的链表。如果想要得到一个元组,必须要加上括号。

十分钟学会python

上一篇:Day 10 动态参数&名称空间,局部全部.函数嵌套&global nonlocal关键字.


下一篇:新版 itextsharp pdf code