zoukankan      html  css  js  c++  java
  • python 基本类型的创建方法

    1、int

    class int(object)
     |  int(x=0) -> integer
     |  int(x, base=10) -> integer
     | 
     |  Convert a number or string to an integer, or return 0 if no arguments
     |  are given.  If x is a number, return x.__int__().  For floating point
     |  numbers, this truncates towards zero.
     | 
     |  If x is not a number or if base is given, then x must be a string,
     |  bytes, or bytearray instance representing an integer literal字面 in the
     |  given base.  The literal can be preceded在什么之前 by '+' or '-' and be surrounded环绕
     |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
     |  Base 0 means to interpret the base from the string as an integer literal.
     |  >>> int('0b100', base=0)
     |  4
    
     1 # 1、没有参数转换为0
     2 print(int())
     3 print('*' * 50)
     4 
     5 # 2、一个数字转换为整数
     6 print(int(10.6))
     7 print('*' * 50)
     8 
     9 # 3、将一个字符串转换为整数
    10 print(int('111', 16))
    11 print(int('111', 10))
    12 print(int('111', 8))
    13 print(int('111', 2))
    14 print('*' * 50)
    15 
    16 # 4、将一个字节流或字节数组转换为整数
    17 print(int(b'111', 16))
    18 print(int(b'111', 10))
    19 print(int(b'111', 8))
    20 print(int(b'111', 2))
    21 print('*' * 50)
    22 
    23 # 5、base=0时,按字面值进行转换
    24 print(int('0x111', 0))
    25 print(int('111', 0))
    26 print(int('0o111', 0))
    27 print(int('0b111', 0))
    28 print('*' * 50)
     1 0
     2 **************************************************
     3 10
     4 **************************************************
     5 273
     6 111
     7 73
     8 7
     9 **************************************************
    10 273
    11 111
    12 73
    13 7
    14 **************************************************
    15 273
    16 111
    17 73
    18 7
    19 **************************************************

    2、bool

    class bool(int)                                                              
     |  bool(x) -> bool                                                     
     | 
     |  Returns True when the argument x is true, False otherwise.                   
     |  The builtins True and False are the only two instances of the class bool.   
     |  The class bool is a subclass of the class int, and cannot be subclassed. 

    3、float

    class float(object)
     |  float(x) -> floating point number
     | 
     |  Convert a string or number to a floating point number, if possible.
    
    1 print(float(123))
    2 print(float('123'))
    1 123.0
    2 123.0

    4、str

    class str(object)
     |  str(object='') -> str
        # 对象转字符串
     |  str(bytes_or_buffer[, encoding[, errors]]) -> str
        # 字节流转字符串
     | 
     |  Create a new string object from the given object. If encoding or
     |  errors is specified, then the object must expose a data buffer
     |  that will be decoded using the given encoding and error handler.
     |  Otherwise, returns the result of object.__str__() (if defined)
     |  or repr(object).
     |  encoding defaults to sys.getdefaultencoding().
     |  errors defaults to 'strict'.
    
     1 # 1、对象转字符串
     2 # 如果对象存在__str__方法,就调用它,否则调用__repr__
     3 print(str([1, 2, 3]))       # 调用了列表的__str__
     4 print([1, 2, 3].__str__())
     5 print(str(type))            # 调用了列表的__repr__
     6 print(type.__repr__(type))
     7 print('*' * 50)
     8 # 注意
     9 print(str(b'123456'))   # 这个是对象转字符串,不是字节流转字符串
    10 print(b'123456'.__str__()) 
    11 print('*' * 50)
    12 
    13 # 2、字节流转字符串
    14 # 第一个参数是字节流对象
    15 # 第二个参数是解码方式,默认是sys.getdefaultencoding()
    16 # 第三个参数是转换出错时的处理方法,默认是strict
    17 import sys
    18 print(sys.getdefaultencoding())
    19 print(str(b'123456', encoding='utf-8'))    # 字节流转字符串的第一种方法
    20 # 字节流转换字符串
    21 print(b'123456'.decode(encoding='utf-8'))  # 字节流转字符串的第二种方法
     1 [1, 2, 3]
     2 [1, 2, 3]
     3 <class 'type'>
     4 <class 'type'>
     5 **************************************************
     6 b'123456'
     7 b'123456'
     8 **************************************************
     9 utf-8
    10 123456
    11 123456

    5、bytearray

    class bytearray(object)
     |  bytearray(iterable_of_ints) -> bytearray<br>    
    # 元素必须为[0 ,255] 中的整数 | bytearray(string, encoding[, errors]) -> bytearray<br>
    # 按照指定的 encoding 将字符串转换为字节序列 | bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer<br>
    # 字节流 | bytearray(int) -> bytes array of size given by the parameter initialized with null bytes<br>
    # 返回一个长度为 source 的初始化数组 | bytearray() -> empty bytes array<br>
    # 默认就是初始化数组为0个元素 | | Construct a mutable bytearray object from: | - an iterable yielding integers in range(256)
    # bytearray([1, 2, 3]) | - a text string encoded using the specified encoding
    # bytearray('你妈嗨', encoding='utf-8') | - a bytes or a buffer object
    # bytearray('你妈嗨'.encode('utf-8')) | - any object implementing the buffer API. | - an integer
    # bytearray(10)
     1 # 1、0个元素的字节数组
     2 print(bytearray())
     3 print('*' * 50)
     4 
     5 # 2、指定个数的字节数组
     6 print(bytearray(10))
     7 print('*' * 50)
     8 
     9 # 3、int类型的可迭代对象,值在0-255
    10 print(bytearray([1, 2, 3, 4, 5]))
    11 print('*' * 50)
    12 
    13 # 4、字符串转字节数组
    14 print(bytearray('12345', encoding='utf-8'))
    15 print('*' * 50)
    16 
    17 # 5、字节流转字符串
    18 print(bytearray(b'12345'))
    19 print('*' * 50)    
     1 bytearray(b'')
     2 **************************************************
     3 bytearray(b'x00x00x00x00x00x00x00x00x00x00')
     4 **************************************************
     5 bytearray(b'x01x02x03x04x05')
     6 **************************************************
     7 bytearray(b'12345')
     8 **************************************************
     9 bytearray(b'12345')
    10 **************************************************

    6、bytes

    class bytes(object)
     |  bytes(iterable_of_ints) -> bytes<br>    # bytes([1, 2, 3, 4])  bytes must be in range(0, 256)
     |  bytes(string, encoding[, errors]) -> bytes<br>    # bytes('你妈嗨', encoding='utf-8')
     |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer<br>    #
     |  bytes(int) -> bytes object of size given by the parameter initialized with null bytes
     |  bytes() -> empty bytes object
     | 
     |  Construct an immutable array of bytes from:
     |    - an iterable yielding integers in range(256)
     |    - a text string encoded using the specified encoding
     |    - any object implementing the buffer API.
     |    - an integer
     1 # 1、一个空字节流
     2 print(bytes())
     3 print('*' * 50)
     4 
     5 # 2、一个指定长度的字节流
     6 print(bytes(10))
     7 print('*' * 50)
     8 
     9 # 3、int类型的可迭代对象,值0-255
    10 print(bytes([1, 2, 3, 4, 5]))
    11 print('*' * 50)
    12 
    13 # 4、string转bytes
    14 print(bytes('12345', encoding='utf-8'))
    15 print('*' * 50)
    16 
    17 print('12345'.encode(encoding='utf-8'))
    18 print('*' * 50)
    19 
    20 # 5、bytearry转bytes
    21 
    22 print(bytes(bytearray([1, 2, 3, 4, 5])))
    23 print('*' * 50)
     1 b''
     2 **************************************************
     3 b'x00x00x00x00x00x00x00x00x00x00'
     4 **************************************************
     5 b'x01x02x03x04x05'
     6 **************************************************
     7 b'12345'
     8 **************************************************
     9 b'12345'
    10 **************************************************
    11 b'x01x02x03x04x05'
    12 **************************************************

    7、list

    class list(object)
     |  list() -> new empty list
     |  list(iterable) -> new list initialized from iterable's items
    
     1 # 1、返回一个空列表
     2 print(list())
     3 
     4 # 2、将一个可迭代对象转换成列表
     5 print(list('string'))
     6 print(list([1, 2, 3, 4]))
     7 print(list({'one': 1, 'two': 2}))
     8 
     9 # 3、参数是一个列表
    10 l = [1, 2, 3, 4]
    11 print(id(l))
    12 l2 = list(l)    # 创建了一个新的列表,与元组不同
    13 print(id(l2))   
    1 []
    2 ['s', 't', 'r', 'i', 'n', 'g']
    3 [1, 2, 3, 4]
    4 ['one', 'two']
    5 35749640
    6 35749704

    字典转列表:

     1 d = {'one': 1, 'two': 2}
     2 
     3 for i in d:
     4     print(i)
     5 print('*'*50)
     6 
     7 for i in d.keys():
     8     print(i)
     9 print('*'*50)
    10 
    11 for i in d.values():
    12     print(i)
    13 print('*'*50)
    14 
    15 for i in d.items():
    16     print(i)
    17 print('*'*50)
    18 
    19 print(list(d))
    20 print(list(d.keys()))
    21 print(list(d.values()))
    22 print(list(d.items()))
    23 print('*'*50)
    24 
    25 print(d)
    26 print(d.keys())
    27 print(d.values())
    28 print(d.items())
    29 print('*'*50)
    30 
    31 print(type(d))
    32 print(type(d.keys()))
    33 print(type(d.values()))
    34 print(type(d.items()))
    35 print('*'*50)
     1 one
     2 two
     3 **************************************************
     4 one
     5 two
     6 **************************************************
     7 1
     8 2
     9 **************************************************
    10 ('one', 1)
    11 ('two', 2)
    12 **************************************************
    13 ['one', 'two']
    14 ['one', 'two']
    15 [1, 2]
    16 [('one', 1), ('two', 2)]
    17 **************************************************
    18 {'one': 1, 'two': 2}
    19 dict_keys(['one', 'two'])
    20 dict_values([1, 2])
    21 dict_items([('one', 1), ('two', 2)])
    22 **************************************************
    23 <class 'dict'>
    24 <class 'dict_keys'>
    25 <class 'dict_values'>
    26 <class 'dict_items'>
    27 **************************************************

    8、tuple

    class tuple(object)
     |  tuple() -> empty tuple
    # 创建一个空的元组 | tuple(iterable) -> tuple initialized from iterable's items
    # 将一个可迭代对象转成元组 | | If the argument is a tuple, the return value is the same object.
    # 如果参数时一个元组,返回一个相同的对象
     1 # 1、返回一个空元组
     2 print(tuple())
     3 
     4 
     5 # 2、将一个可迭代对象转换成元组
     6 print(tuple('string'))
     7 print(tuple([1, 2, 3, 4]))
     8 print(tuple({'one': 1, 'two': 2}))
     9 
    10 
    11 # 3、参数是一个元组
    12 tp = (1, 2, 3, 4)
    13 print(id(tp))
    14 tp2 = tuple(tp)
    15 print(id(tp2))
    1 ()
    2 ('s', 't', 'r', 'i', 'n', 'g')
    3 (1, 2, 3, 4)
    4 ('one', 'two')    # 参数是字典的时候,返回的是键值的元组
    5 35774616
    6 35774616

    字典转元组:

     1 d = {'one': 1, 'two': 2}
     2 
     3 for i in d:
     4     print(i)
     5 print('*'*50)
     6 
     7 for i in d.keys():
     8     print(i)
     9 print('*'*50)
    10 
    11 for i in d.values():
    12     print(i)
    13 print('*'*50)
    14 
    15 for i in d.items():
    16     print(i)
    17 print('*'*50)
    18 
    19 print(tuple(d))
    20 print(tuple(d.keys()))
    21 print(tuple(d.values()))
    22 print(tuple(d.items()))
    23 print('*'*50)
    24 
    25 print(d)
    26 print(d.keys())
    27 print(d.values())
    28 print(d.items())
    29 print('*'*50)
    30 
    31 print(type(d))
    32 print(type(d.keys()))
    33 print(type(d.values()))
    34 print(type(d.items()))
    35 print('*'*50)
    one
    two
    **************************************************
    one
    two
    **************************************************
    1
    2
    **************************************************
    ('one', 1)
    ('two', 2)
    **************************************************
    ('one', 'two')
    ('one', 'two')
    (1, 2)
    (('one', 1), ('two', 2))
    **************************************************
    {'one': 1, 'two': 2}
    dict_keys(['one', 'two'])
    dict_values([1, 2])
    dict_items([('one', 1), ('two', 2)])
    **************************************************
    <class 'dict'>
    <class 'dict_keys'>
    <class 'dict_values'>
    <class 'dict_items'>
    **************************************************

    9、dict

    class dict(object)
     |  dict() -> new empty dictionary    # 空字典
     |  dict(mapping) -> new dictionary initialized from a mapping object's
     |      (key, value) pairs<br>    # dict([('one', 1), ('two', 2)])
     |  dict(iterable) -> new dictionary initialized as if via:
     |      d = {}
     |      for k, v in iterable:
     |          d[k] = v
     |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
     |      in the keyword argument list.  For example:  dict(one=1, two=2)
    
     1 # 1、空字典
     2 print(dict())
     3 print('*' * 50)
     4 
     5 # 2、从一个映射对象创建字典
     6 print(dict([('one', 1), ('two', 2)]))
     7 print('*' * 50)
     8 
     9 # 3、从一个带key和value的可迭代对象创建字典
    10 d = {'one': 1, 'two': 2}
    11 dt = {}
    12 for k, v in d.items():
    13     dt[k] = v
    14 print(dt)
    15 print('*' * 50)
    16 
    17 # 4、以name=value对创建字典
    18 print(dict(one=1, two=2))
    1 {}
    2 **************************************************
    3 {'one': 1, 'two': 2}
    4 **************************************************
    5 {'one': 1, 'two': 2}
    6 **************************************************
    7 {'one': 1, 'two': 2}

    10、set

    class set(object)
     |  set() -> new empty set object
     |  set(iterable) -> new set object
    
    1 # 1、创建空集合
    2 print(set())
    3 
    4 # 2、可迭代对象转换为集合
    5 print(set([1, 2, 1, 2]))
    1 set()      # 空集合这样表示,{}表示字典
    2 {1, 2}

    11、frozenset

    class frozenset(object)
     |  frozenset() -> empty frozenset object
     |  frozenset(iterable) -> frozenset object
     | 
     |  Build an immutable unordered collection of unique elements.
    # 与set的区别是不可变得
     1 # 1、创建空集合
     2 print(frozenset())
     3 
     4 # 2、可迭代对象转换为集合
     5 fs = frozenset([1, 2, 1, 2])
     6 print(fs)
     7 
     8 # 3、为set和frozenset对象添加元素
     9 s = set((100, ))
    10 s.add(10)
    11 print(s)
    12 
    13 fs.add(10)   
    1 frozenset()
    2 frozenset({1, 2})
    3 {10, 100}
    4 Traceback (most recent call last):
    5   File "1.py", line 14, in <module>
    6     fs.add(10)   
    7 AttributeError: 'frozenset' object has no attribute 'add'

    12、complex

    class complex(object)
     |  complex(real[, imag]) -> complex number
     | 
     |  Create a complex number from a real part and an optional imaginary part.
     |  This is equivalent to (real + imag*1j) where imag defaults to 0.
    
    1 print(complex(10))
    2 print(complex(10, 10))
    3 a = 10 + 0j
    4 print(a)
    5 print(a == 10)
    1 (10+0j)
    2 (10+10j)
    3 (10+0j)
    4 True

    13、type

    class type(object)
     |  type(object_or_name, bases, dict)
    # 创建一个类 | type(object) -> the object's type
    # 查看这个对象的类型 | type(name, bases, dict) -> a new type
    #
     1 # type功能1,判断对象的类型
     2 print(type(int))
     3 print(type(100))
     4 
     5 
     6 # type功能2,动态创建类
     7 # 第一个参数是字符串
     8 # 第二个参数是父类的元组
     9 # 第三个参数是属性的字典
    10 class Animal():
    11     pass
    12 
    13 Dog = type('Dog', (Animal,), {})
    14 dog = Dog()
    15 
    16 print(type(Dog))
    17 print(type(dog))
  • 相关阅读:
    函数
    A × B problem
    求n的阶乘
    自己构建一个vector函数
    int与string的互相转化
    列一列(斐波那契数列)
    找一找
    c++大数计算模板
    JSON--js中 json字符串转对象、对象转字符串
    JSON
  • 原文地址:https://www.cnblogs.com/gundan/p/8257603.html
Copyright © 2011-2022 走看看