Python笔记【七】

本文为博主原创,未经许可严禁转载。
本文链接:https://blog.csdn.net/zyooooxie/article/details/108998778

今天我看到 https://blog.csdn.net/zyooooxie/article/details/84422924 单篇过了1w访问量;特地加更。继续分享下 最近学习Python 的收获, 这是我的博客里 学习python的category

个人博客:https://blog.csdn.net/zyooooxie

字典推导式

我在 笔记【一】 提到过 列表推导式,在 笔记【六】 提到过 生成器表达式;

这儿来说下:字典推导式(dictionary comprehension)

{key:value for variable in iterable [if expression]}


def test_dict_derivation():
    test_dict = {
    
    '1q': 'v1', '2w': 'v2', '3e': 3, '4r': 4}

    # 更换key、value
    new_dict = {
    
    v: k for k, v in test_dict.items()}
    print(new_dict, type(new_dict))

    new_dict = {
    
    v: k for k, v in test_dict.items() if isinstance(v, int)}
    print(new_dict)         # key都是int

    new_dict = {
    
    v: v if isinstance(v, int) else k for k, v in test_dict.items()}
    print(new_dict)

bin()、oct()、hex()、int()


def test_1():
    """
    手动计算进制转换
    :return:
    """
    # 4*10**2 + 3*10**1 + 1*10**0 = 400 + 30 + 1            # 十进制,逢10进1

    # 二进制转十进制
    # 10001000100 = 1*2**10 + 0*2**9 + 0*2**8 + 0*2**7 + 1*2**6 + 0*2**5 + 0*2**4 + 0*2**3 + 1*2**2 + 0*2**1 + 0*2**0
    print(0b10001000100)                # 1092          python中二进制的数值以0b开头
    print(int('10001000100', 2))        # 1092
    print(2**10 + 2**6 + 2**2)          # 1092

    # 八进制转十进制
    # 10001000100 = 1*8**10 + 0*8**9 + 0*8**8 + 0*8**7 + 1*8**6 + 0*8**5 + 0*8**4 + 0*8**3 + 1*8**2 + 0*8**1 + 0*8**0
    print(0o10001000100)                # 1074004032         在python中,八进制的数值使用0o开头
    print(int('10001000100', 8))        # 1074004032
    print(8**10 + 8**6 + 8**2)          # 1074004032

    # 十六进制转十进制
    # 十六进制是逢16进1,因此单个位上的数值会超过9, 超过9的部分依次使用a, b, c, d, e, f, 分别代表10, 11, 12, 13, 14, 15。
    # 10001000100 = 1*16**10 + 0*16**9 + 0*16**8 + 0*16**7 + 1*16**6 + 0*16**5 + 0*16**4 + 0*16**3 + 1*16**2 + 0*16**1 + 0*16**0
    print(0x10001000100)                         # 1099528405248         python中十六进制的数值以0x开头
    print(int('10001000100', 16))                # 1099528405248
    print(16**10 + 16**6 + 16**2)               # 1099528405248
    

其他进制 转化为十进制

https://docs.python.org/zh-cn/3.7/library/functions.html#int


def test_int():
    # 返回一个使用数字或字符串 x 生成的整数对象,或者没有实参的时候返回 0
    a = int()   # base=10
    print(a)

    # Base 0 means to interpret the base from the string as an integer literal.
    a1 = int('123456', base=0)
    print(a1)

    # 使用int函数可以将二进制,八进制,十六进制的数值转成十进制数值,而且字符串的开头可以不携带进制的标识,

    b = int('111', 2)
    print(b)

    b1 = int('0b111', 2)
    print(b1)

    print(int(bin(111), 2))

    c = int('111', 8)
    print(c)

    c1 = int('0o111', 8)
    print(c1)

    print(int(oct(111), 8))

    # d = int('111', 10)
    # print(d)

    e = int('111', 16)
    print(e)

    e1 = int('0x111', 16)
    print(e1)

    e2 = int(hex(111), 16)
    print(e2)


十进制 转化为其他进制

https://docs.python.org/zh-cn/3.7/library/functions.html#bin

https://docs.python.org/zh-cn/3.7/library/functions.html#oct

https://docs.python.org/zh-cn/3.7/library/functions.html#hex


def test_bin():
    # 十进制转二进制:一个前缀为“0b”的二进制字符串
    int_p = 81
    print(bin(int_p))
    print(bin(int_p * -1))

    # 如果不一定需要前缀“0b”,还可以使用如下的方法
    a = format(81, 'b')
    print(a)

    # 其他进制
    print(bin(0o77327))
    print(bin(0x1e212f))


def test_oct():
    # 十进制转八进制:一个前缀为“0o”的八进制字符串。
    print(oct(12))
    print(oct(122))

    print(oct(0x122eef82))
    print(oct(0b111001))


def test_hex():
    # 十进制转16进制:以“0x”为前缀的小写十六进制字符串。
    print(hex(65))

    print(hex(0o1277532))
    print(hex(0b10011))


def test_summary():
    # 十进制 转换为 其他进制

    t = 6600
    print(format(t, 'b'))       # 转换成2进制
    print(format(t, 'o'))       # 转换成8进制
    print(format(t, 'd'))       # 转换成10进制
    print(format(t, 'x'))       # 转换成16进制   小写字母表示
    print(format(t, 'X'))       # 转换成16进制   大写字母表示

    print('{:b}'.format(t))
    print('{:o}'.format(t))
    print('{:d}'.format(t))
    print('{:x}'.format(t))
    print('{:X}'.format(t))

    print(bin(t)[2:])
    print(oct(t)[2:])
    print(int(t))
    print(hex(t)[2:])


delattr()、getattr()、hasattr()、setattr()

https://docs.python.org/zh-cn/3.7/library/functions.html#delattr

https://docs.python.org/zh-cn/3.7/library/functions.html#getattr

https://docs.python.org/zh-cn/3.7/library/functions.html#hasattr

https://docs.python.org/zh-cn/3.7/library/functions.html#setattr


class MyClass(object):

    abc = 'abc_类属性'
    ABC = 'ABC_类属性'

    def __init__(self, value, value2):
        self.value = value
        self.ABC = 'ABC实例属性值'
        self.abc = value2



def test_delattr():
    # 实参是一个对象和一个字符串。该字符串必须是对象的某个属性。如果对象允许,该函数将删除指定的属性
    # delattr(x, 'foobar') 等价于 del x.foobar
    c = MyClass('del_1', 'del_2')
    print(c.__dict__)

    delattr(c, 'value')
    print(c.__dict__)

    del c.ABC
    print(c.__dict__)

    # 动态删除属性(根据用户输入 删除对象的属性)
    delattr(c, input('yao删除的:'))
    print(c.__dict__)


def test_getattr():
    # 返回对象命名属性的值。name 必须是字符串。
    a = getattr(list, 'extend')
    print(a)

    # 如果该字符串是对象的属性之一,则返回该属性的值。例如, getattr(x, 'foobar') 等同于 x.foobar。如果指定的属性不存在,且提供了 default 值,则返回它,否则触发 AttributeError。
    c = MyClass('get_1', 'get_2')
    print(getattr(c, 'ABC'))
    print(c.ABC)

    print(getattr(c, 'value'))

    # print(getattr(c, 'abc123'))     # AttributeError: 'MyClass' object has no attribute 'abc123'

    print(getattr(c, 'abc123', '没有的'))


def test_hasattr():
    # 该实参是一个对象和一个字符串。如果字符串是对象的属性之一的名称,则返回 True,否则返回 False。
    a = hasattr(list, 'append')
    print(a)

    c = MyClass('has_1', 'has_2')
    print(hasattr(c, 'ABC'))
    print(hasattr(c, 'abc'))
    print(hasattr(c, 'abc123'))


def test_setattr():
    # setattr其参数为一个对象、一个字符串和一个任意值。
    # 字符串指定一个现有属性或者新增属性。 函数会将值赋给该属性,只要对象允许这种操作。

    c = MyClass('set_1', 'set_2')
    print(c.__dict__)

    setattr(c, 'ABC', 123)
    print(c.__dict__)

    c.ABC = 987
    print(c.__dict__)

    # 创建新属性
    c.new = 888
    print(c.__dict__)

    setattr(c, 'NEW', 666)
    print(c.__dict__)


ord() 和 chr()

https://docs.python.org/zh-cn/3.7/library/functions.html#ord

https://docs.python.org/zh-cn/3.7/library/functions.html#chr


# 在计算机里,一切都是用二进制存储的,比如 a 这个字母,在计算机里,用 0110 0001 这个8个bit来表示,8个bit就是一个字节。
# 所谓ascii,就是一个字符编码,它规定了英文中的各种字符在计算机里表示形式。
# ascii码作为一种字符编码,可以表示128个字符与二进制之间的关系,

# 关于ASCII表,
# 数字0~9在ascii表里的编码范围是48~57
# 小写字母在ascii表里的编码范围是97~122
# 大写字母在ascii表里的编码范围是65~90

# 在python3中,字符串是以unicode编码的


def test_ascii():
    en_str = 'a'
    # 字符a的二进制编码是“0110 0001”,把这个二进制转成10进制就是97

    assert format(ord(en_str), 'b') == '1100001'
    print(bin(ord(en_str)))         # 0b1100001

    print(ord(en_str))              # 97
    print(int('1100001', 2))        # 97


def test_ord():
    # 对单个Unicode字符的字符串,返回代表它的 Unicode 码点的整数
    print(ord('a'))
    print(ord('A'))
    print(ord('0'))

    print(ord('我'))
    print(ord('#'))

    # 只能接受一个字符
    # print(ord('#@'))            # TypeError: ord() expected a character, but string of length 2 found


def test_chr():
    # 返回 Unicode 码位为整数 i 的字符 的 str。
    # 实参的合法范围是 0 到 1114111

    a = chr(35)         # '#'
    print(a, type(a))

    a = chr(25105)       # '我'
    print(a)

本文链接:https://blog.csdn.net/zyooooxie/article/details/108998778

交流技术 欢迎+QQ 153132336 zy
个人博客 https://blog.csdn.net/zyooooxie

おすすめ

転載: blog.csdn.net/zyooooxie/article/details/108998778