# coding:utf-8
def exchange_mask(mask):
"""
轉換子網掩碼格式
"""
# 計算二進制字符串中 '1' 的個數
count_bit = lambda bin_str: len([i for i in bin_str if i=='1'])
# 分割字符串格式的子網掩碼爲四段列表
mask_splited = mask.split('.')
# 轉換各段子網掩碼爲二進制, 計算十進制
mask_count = [count_bit(bin(int(i))) for i in mask_splited]
return sum(mask_count)
if __name__ == '__main__':
print exchange_mask('255.255.0.0')
===================================================================
def exchange_maskint(mask_int): bin_arr = ['0' for i in range(32)] for i in range(mask_int): bin_arr[i] = '1' tmpmask = [''.join(bin_arr[i * 8:i * 8 + 8]) for i in range(4)] tmpmask = [str(int(tmpstr, 2)) for tmpstr in tmpmask] return '.'.join(tmpmask) if __name__ == '__main__': print exchange_maskint(24)