Python学习——复习3次课(11月30日)

任务:

2.6 使用for循环遍历文件
2.7 使用while循环遍历文件
2.8 统计系统剩余的内存
2.9 数据类型转换计算(计算mac地址)
3.0 数据类型转换(列表与字典相互转换)

笔记:

2.6 使用for循环遍历文件

#!/usr/bin/env python
fd = open('/tmp/hello.txt')
  for line in fd:
    print line,


2.7 使用while循环遍历文件

while True:

#!/usr/bin/env python
fd = open('/tmp/hello.txt')
while True:
  line = fd.readline()
  if not line:
    break
    print line,
fd.close()


2.8 统计系统剩余的内存

Python学习——复习3次课(11月30日)


2.9 数据类型转换计算(计算mac地址)


3.0 数据类型转换(列表与字典相互转换)

对元组进行转换
fruits = ('apple','banana','orange')

#元组转换为列表:
list(fruit)

#元组不能直接转换为字典,附:
#元组转换为字符串:
fruits.__str__()

对列表的转换
fruit_list = ['apple','banana','orange']

#列表转换为元组:
tuple(fruit_list)

#列表不能直接转换为字典,附:
#列表转换为字符串:
str(fruit_list)

对字典的转换

fruit_dict = {'apple':1, 'banana':2, 'orange':3}

#将字典的key转换为元组:
tuple(fruit_dict)
#将字典的value转换为元组:
tuple(fruit_dict.value())

#将字典的key转换为列表:
list(fruit_dict)
#将字典的value转换为列表:
list(fruit_dict.value())

#附:
#将字典转换为字符串:
str(fruit_dict)


对字符串的转换

#将字符串转换为元组:
str = "(1,2,3)"
tuple(eval(str))
#将字符串转换为列表:
str = "(1,2,3)"
list(eval(str))
#将字符串转换为字典:
str = "{'a':1 ,'b',2}"
eval(str)