摘要

各数据结构间转换

目的

  • 掌握各个数据结构直接的转换
  • 掌握例子

内容

统计内存
#打开内存值存放文件
with open('/proc/meminfo') as fd:
    for line in fd:
        #判断相应开头
        if line.startswith('MemTotal'):
            #取出相应值,spilt()默认以空格区分,返回一个列表
            total = line.split()[1]
            continue
        if line.startswith('MemFree'):
            free = line.split()[1]
            break

#打印内存值,以M的单位
print("%.2f : %.2f" % (int(total)/1024.0),(int(free)/1204.0))
#比值
print(int(free)/ int(total))

#psutil模块也可以统计系统相应信息
import psutil
mem = psutil.virtual_memory()
print(psutil.virtual_memory())
print '内存相关信息'
print(mem.total,mem.used,mem.percent)
cpu_info = psutil.cpu_times()
print(cpu_info.user)
print 'cpu逻辑个数'
print(psutil.cpu_count())
print '物理个数'
print(psutil.cpu_count(logical=False))

数据结构转换
#数据类型转换
#十六进制转换到十进制
print(int('12',16))
print(int('a',16))
#十进制转换成十进制
print(hex(10))
#数字转换成字符串
str(10)


##例子,mac地址
macaddr = '00:0C:29:D1:6F:0F'
prefix_mac = macaddr[:-2]
last_two = macaddr[-2:]
plus_one = int(last_two,16) + 1
if plus_one < 10:
    new_last_two = hex(plus_one)[2:]
    new_last_two = '0' + new_last_two
else:
    new_last_two = hex(plus_one)[2:]
    if len(new_last_two) == 1:
        new_last_two = '0' + new_last_two
new_mac = prefix_mac + new_last_two
print(new_mac.upper())

#字符串转列表
print list('abc')
#列表转换成字符串
print '.'.join(list('abc'))
#字符串转元组
tuple('abc')
#元组转字符串
''.join(tuple('abc'))
#字典转换成列表
dic = {'a':1,'b':2}
print dic.items()
#列表转换成列表,只要列表里面都是元组才能转
print dict(dic.items())


总结

  • 各数据机构转换
  • 取出内存值的例子理解,但没在linux下运行,后期要运行下
posted on 2017-12-29 23:41  siaspedro  阅读(140)  评论(0编辑  收藏  举报