Python 初体验(三)

  • 交换元素

python的交换元素的方法非常简单,一般的编程语言中需要使用temporary variables,但是python中不需要

>>> a = 1
>>> b =2
>>> c =3
>>> a,b,c = c ,b,a
>>> a
3
>>> b
2
>>> c
1
>>>

  • construct a dictionary without excessive quoting

>>> def makedic(**dic):
    return dic

>>> data = makedic(red = 1, black = 2, blue = 3)

  • 关于调用module

编写了一个module check.py用来检查一个字典中是否有某个索引。文件如下:

check.py

def check(key, **dic):
    if dic.has_key(key):
        print dic[key]
    else:
        print 'not found'

现在我想调用这个函数了,先定义了一个字典:

>>> def makedic(**k):
    return k

>>> data = makedic(red=1,green=2,blue=3)
>>> data
{'blue': 3, 'green': 2, 'red': 1}

然后import check这个module,运行check函数:

>>> import check
>>> check('green',**data)

Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    check('green',**data)
TypeError: 'module' object is not callable
报错,提示module object is not callable,要解决这个问题记住导入的module不想直接在文件中定义的函数一样可以直接使用,需要在module object中使用:

>>> check.check('green',**data)
2
>>> check.check('black',**data)
not found

这样就可以得到正确的运行结果了。

或者直接将check导入,使用语句 from check import *(*表示将check中的所有函数,variable导入)

通过if __name__ == '__main__': 可以判断一个module是自己在运行 还是被import了运行

另外值得一提的是,python有一种更加简单的方法检查索引是否在字典中:

print data.get(‘green’,’not found ’)   即可

  • python作为脚本语言方便的处理能力

有个文件a.txt,里面包含了发散的数字,中间至少有空格,也有空行。如何提取这些数字呢?python用两句话可以解决这个问题

>>> f = open('a.txt','r')
>>> n = f.read().split()
>>> n
['123', '345', '123', '456', '123', '33', '1', '12', '12', '23', '456']

  • how to run python module in command window?

script.py是这样一个文件,如何在cmd中运行?

import sys, math # load system and math module
r = float(sys.argv[1]) # extract the 1st command-line argument
s = math.sin(r)
print "Hello, World! sin(" + str(r) + ")=" + str(s)

方法是:打开script.py所在目录,输入 script.py 1.4

输出是:Hello, World! sin(1.4)=0.985449729988

  • ways to explore python

type(…)

dir(…)

help(…)

  • 复制

在python中复制list时,一定要注意复制方法。如果仅仅将一个list的name赋给另外一个list,那么得到的list和原list指向同一块内存。会造成无法预料的后果。

例如:

>>> a = [1,2,3]
>>> b = a
>>> del a[0]
>>> a
[2, 3]
>>> b
[2, 3]
>>> a=[1,2,3]
>>> b=a[:]                       ##推荐用这种方法进行复制
>>> del a[0]
>>> a
[2, 3]
>>> b
[1, 2, 3]

原文地址:https://www.cnblogs.com/bovine/p/2262524.html