列表
IT培训的老师说,一种常用的列表类型是 tuple,它是不可变的.在 tuple 中载入一系列值之后,您不会更改它.Tuple 可以包含数字、字符串、变量,甚至其他 tuples.Tuples 从 0 开始建立索引,这很正常;您可以使用 -1 索引访问最后一个项目.您还可以对 tuple 运行一些函数(请参见清单 9).
清单 9. Tuples
items = (1, mutt, 'Honda', (1,2,3))
print items[1] #prints Kafka
print items[-1] #prints (1,2,3)
items2 = items[0:2] #items2 now contains (1, 'Kafka') thanks to slice operation
'Honda' in items #returns TRUE
len(items) #returns 4
items.index('Kafka') #returns 1, because second item matches this index location
列表与 tuple 类似,只不过它们是可变的.创建列表之后,您可以添加、删除和更新列表中的值.列表使用方括号,而不是圆括号(()),如清单 10 所示.
清单 10. 列表
groceries = ['ham','spam','eggs']
len(groceries) #returns 3
print groceries[1] #prints spam
for x in groceries:
print x.upper() #prints HAM SPAM EGGS
groceries[2] = 'bacon'
groceries #list is now ['ham','spam','bacon']
groceries.append('eggs')
groceries #list is now ['ham', 'spam', 'bacon', 'eggs']
groceries.sort()
groceries #list is now ['bacon', 'eggs', 'ham', 'spam']
字典类似于关联数组或散列;它使用键值对来存储和限制信息.但它不使用方括号和圆括号,而是使用尖括号.与列表类似,字典是可变的,这意味着您可以添加、删除和更新其中的值(请参见清单 11).
清单 11. 字典
colorvalues = {'red' : 1, 'blue' : 2, 'green' : 3, 'yellow' : 4, 'orange' : 5}
colorvalues #prints {'blue': 2, 'orange': 5, 'green': 3, 'yellow': 4, 'red': 1}
colorvalues['blue'] #prints 2
colorvalues.keys() #retrieves all keys as a list:
#['blue', 'orange', 'green', 'yellow', 'red']
colorvalues.pop('blue') #prints 2 and removes the blue key/value pair
colorvalues #after pop, we have:
#{'orange': 5, 'green': 3, 'yellow': 4, 'red': 1}

回页首
在 Python 中创建一个简单的脚本
现在,您已经对 Python 有了一定的了解.接下来,我们将创建一个简单的 Python 脚本.该脚本将读取位于您的服务器 /tmp 目录下的 PHP 会话文件的数量,并在日志文件中写入摘要报告.在该脚本中,您将学习如何导入特定函数的模块,如何使用文件,以及如何写入日志文件.您还将设置一系列变量来跟踪所收集的信息.
清单 12 展示了整个脚本.打开一个编辑器,并将代码粘贴到其中,然后在系统中将该文件保存为 tmp.py.然后,对该文件运行 chmod + x,使它成为可执行文件(假定您使用 UNIX? 系统).
清单 12. tmp.py
#!/usr/bin/python
import os
from time import strftime
stamp = strftime("%Y-%m-%d %H:%M:%S")
logfile = '/path/to/your/logfile.log'
path = '/path/to/tmp/directory/'
files = os.listdir(path)
bytes = 0
numfiles = 0
for f in files:
if f.startswith('sess_'):
info = os.stat(path + f)
numfiles += 1
bytes += info[6]
if numfiles > 1:
title = 'files'
else:
title = 'file'
string = stamp + " -- " + str(numfiles) + " session " \
+ title +", " + str(bytes) + " bytes\n"
file = open(logfile,"a")
file.writelines(string)
file.close()
在第一行中,您可以看到一个 hash-bang 行:它用于标识 Python 解释器的位置.在我的系统中,它位于 /usr/bin/python.请根据系统需求调整这一行.
接下来的两行用于导入特定的模块,这些模块将帮助您执行作业.考虑到脚本需要处理文件夹和文件,因此您需要导入 os 模块,因为其中包含各种函数和方法,可帮助您列出文件、读取文件和操作文件夹.您还需要写入一个日志文件,因此可以为条目添加一个时间戳 - 这就需要使用时间函数.您不需要所有时间函数,只需要导入 strftime函数即可.
以上就是IT培训给大家做的内容详解,更多关于IT的学习,请继续关注IT培训