Python Revisited Day 02(データ型)

20968 ワード

目次
  • Pythonキーワード
  • 整数
  • 整数変換関数
  • 整数ビット論理オペレータ
  • 浮動小数点タイプ
  • mathモジュール関数と定数
  • 複数
  • 正確な10進数decimal
  • 文字列
  • str.format()
  • フォーマット規約

  • Pythonキーワード
    and continue except global lambda pass while as def False if None raise with assert del finally import nonlocal return yield break elif for in not True calss else from is or try
    1 + True # 2

    整数
    0b111 # 7 0b   
    0o111 # 73 0o    
    0x111 # 273 0x     
    divmod(5,2) # (2,1)         
    pow(2, 3) # 2**3 8  
    pow(3, 4, 2) # (3 ** 4) % 2 1
    round(3.1415926, 4) #3.142 

    整数変換関数
    bin(7) # '0b111'          
    hex(273) # '0x111'          
    oct(73)  # '0o111'         
    int('A4', 16)  #164
    int('A4', 15) #154
    int('A4', 36) #364
    int('A4', 37) #  
    #int(s, base)  base 2-36     s  base           9 + 26       35

    整数ビット論理オペレータ
    負数のバイナリ表示Pythonビットオペレータ
    1|2 # 3
    0b01|0b11 #3  |   or                   -3    ‘011111101’
    1^3 #XOR         1    0
    1&3 # 1  AND    
    1 << 3 # 8  1  3  i*(2**j)
    5 >>2 #  
    ~3 # -4   3    (             )

    浮動小数点の種類
    math.floor(3.6)  #3
    math.ceil(3.4) #4
    num = 4 / 3
    float.is_integer(num) #false
    float.as_integer_ratio(2.75) #(11, 4)  11/4
    

    mathモジュール関数と定数
    import math
    math.acos()
    math.acosh()
    math.asin()
    math.atan()
    math,atan2(y, x)
    math.atanh()
    math.ceil()
    math.copysign(x, y) # x      y   
    math.cos()
    math.cosh()
    math.degrees(r) #    r        
    math.e #     e
    math.exp()
    math.fabs(-1) #1.0
    math.factorial(5) #120 5!    
    math.floor()
    math.fmod(x,y) # x % y better?
    math.frexp(6) #(0.75, 3)   0.75 * 2 ^(3)             
    math.fsum([1, 2, 3]) # 6.0
    math.hypot(x, y)   #sqrt(x^2 + y ^2)
    math.isinf()  #     infinity
    math.isnan()
    math.ldexp(m ,e) #  m * 2^e  math.frexp  
    math.log(x, b) #b          e
    math.log10(x)
    math.log1p(x)#ln(1+x)
    math.modf(2.2) #(0.20000000000000018, 2.0)
    math.pi
    math.pow(x, y) # x^y
    math.radians(d) #     
    math.sin()
    math.sinh()
    math.sqrt()
    math,tan()
    math.tanh()
    math.trunc(1.333)  # 1 int()

    複数
    c = 2 + 3j
    c.real # 2.0
    c.imag #3.0
    c.conjugate() #(2-3j)
    complex(1.2)#(1.2+0j)
    complex('1+2j') #(1+2j)

    正確な10進数decimal
    import decimal
    a = decimal.Decimal(1234)
    a  #Decimal('1234')
    decimal.Decimal(12.34) #Decimal('12.339999999999999857891452847979962825775146484375')
    decimal.Decimal('12.34') #Decimal('12.34')
    

    mathとcmathモジュールはdecimalの処理に適していない.Decimalsですが、mathモジュールはdecimalとしていくつかの関数を提供します.Decimalの方法で使用します.math.exp(x)のxはdecimalである.Decimalの場合、x.exp()を使うべきです.
    a = decimal.Decimal('12.34')
    math.exp(a)#228661.9520568098
    a.exp() #Decimal('228661.9520568098295904159251')

    文字列
    s = 'The waxwork man'
    s = s[:12] + 'wo' + s[12:]
    s  #'The waxwork woman'
    s[::-1]  #'namow krowxaw ehT'
    s * 2 #'The waxwork womanThe waxwork woman'
  • s.capitalize()先頭文字が大文字に変更
  • s.center(width,char)は、sの中間部分のサブ文字列の長さをwidthとして返し、charで埋め込む
  • s.cont(t,start,end)start~end中子文字列tの出現回数を返す
  • s.encode(encoding, err)
  • s.endswith(x,start,end)文字列がxで終わるとTrue
  • を返す
  • s.expandtabs(size)文字列のタブは、8個または数のスペース置換
  • を使用します.
  • s.find(t,start,end)戻りt sの中で最も左の位置に戻り-1
  • s.format(...) フォーマット
  • s.index(t,start,end)とfind?
  • s.isalnum()sが空でなく、各文字がアルファベットまたは数値である場合はTrue
  • を返します.
  • s.isalpha() ...すべてアルファベットです...
  • s.isdecimal()
  • s.isdigit()
  • s.isidentifier() ...有効な識別子...
  • s.islower() ...少なくとも1つの小文字可能な文字があり、小文字可能な文字はすべて小文字です...
  • s.isupper()
  • s.isnumeric()
  • s.isprintable()改行を含まない
  • s.issapce() ...空白の文字...
  • s.istitle()空でない頭文字の大文字の文字列は、True'~231313 A'True
  • を返します.
  • s.join(seq) '1'.join('ABC') 'A1B1C'
  • s.ljust(width, char)
  • s.lower()が小文字になる
  • str.format()
    'The novel {0} was published in {1}'.format('Hard Times', 1854)
    #'The novel Hard Times was published in 1854'
    'The novel {} was published in {}'.format('Hard Times', 1854)
    #'The novel Hard Times was published in 1854'
    '{{{0}}} {1} ; -}}'.format('The amount due is $', 200)
    #'{The amount due is $} 200 ; -}'      {{ -> {   }} -> }
    '{who} turned {age} this year'.format(who='she', age=88)
    #'she turned 88 this year'
    '{who} turned {age} this year'.format(who='she', age=88, 99)
    #SyntaxError: positional argument follows keyword argument
    '{who} turned {age} this year'.format(who='she', age=88, name = 99)
    #'she turned 88 this year'
    'The {who} was {0} last week'.format(12, who='boy')
    #'The boy was 12 last week'
    'The {who} was {0} last week'.format(who='boy', 12)
    #SyntaxError: positional argument follows keyword argument
    '{who} turned {age} this year'.format(99, who='she', age=88)
    #'she turned 88 this year'             !!!
    stock = ['paper', 'envelopes', 'notepads']
    'We have {0[1]} and {0[2]} in stock'.format(stock)
    #'We have envelopes and notepads in stock'
    'We have {[1]} and {[2]} in stock'.format(stock)
    #tuple index out of range
    d = dict(animal = 'elephant', weight = 12000)
    'The {0[animal]} weighs {0[weight]}kg'.format(d)
    #'The elephant weighs 12000kg'
    import math
    import sys
    'math.pi=={0.pi} sys.maxunicode=={1.maxunicode}'.format(math,sys)
    #'math.pi==3.141592653589793 sys.maxunicode==1114111' 
    #            {}         copy,                        ,     。
    element = 'Silver' 
    number = 47
    'The {number} is {element}'.format(**locals())
    #'The 47 is Silver' 
    #locals()          ,**         (*=*, *=*)       ,          ,      ,       。   ,
    'The {animal} weights, {weight}kg'.format(**d)
    #'The elephant weights, 12000kg'
    '{}  {}'.format(*['Eric', 'better'])
    #'Eric  better'

    へんかん
    decimal.Decimal('3.1415926')
    #Decimal('3.1415926')
    print(decimal.Decimal('3.1415926'))
    #3.1415926

    上記の2つの方式では、第1の方式は表象形式と呼ばれ、この形式の用途はPythonによって解釈され、その表現を再構築するオブジェクトを提供することである.(よくわかりません...)2つ目はdecimalを文字列形式で対す.Decimalは、読みやすい形式を目指して展示されています.データ型の通常の動作を書き換え、文字列形式またはイメージ形式を強制することができます.
  • s文字列形式の強制使用
  • r強制使用表象形式
  • aは、表象形式を強制的に使用するために使用されるが、ASCII文字
  • に限定される.
    '{0} {0!s} {0!r} {0!a}'.format(decimal.Decimal('3.14'))
    #"3.14 3.14 Decimal('3.14') Decimal('3.14')"
    '{0} {0!s} {0!r} {0!a}'.format('ABDCE\u308b')
    #"ABDCEる ABDCEる 'ABDCEる' 'ABDCE\\u308b'"
    '{0} {0!s} {0!r} {0!a}'.format('ABDCEる')
    #"ABDCEる ABDCEる 'ABDCEる' 'ABDCE\\u308b'"
    '{0} {0!s} {0!r} {0!a}'.format('\\\\\\')
    #"\\\\\\ \\\\\\ '\\\\\\\\\\\\' '\\\\\\\\\\\\'"

    フォーマット規約
    出力フォーマットの正確な制御のための基本構文::fill align sign#0 width,.precision type文字列のフォーマット規則は、コロン(:)によって導入され、後にオプションの1つの充填文字、1つの整列文字(それぞれ左上右に対応)、後に最小幅に従い、最大幅を制定する必要がある場合は、その後に使用する.maxwidth
    '{0}'.format(s)
    #'Eric hurt the little girl!'
    '{0:40}'.format(s)   #         minimum width 40
    #'Eric hurt the little girl!               '
    '{0:>40}'.format(s)   #>      
    #'              Eric hurt the little girl!'
    '{0:^40}'.format(s)  #^     
    #'       Eric hurt the little girl!       '
    '{0:?^40}'.format(s)  #  ^                 ?
    #'???????Eric hurt the little girl!???????'
    '{0:.<40}'.format(s)  # <              .            ‘

    フォーマット規約の内部に置換フィールドを含めることは可能です.
    maxwidth = 20
    '{0}'.format(s[:maxwidth])   #      
    #'Eric hurt the little'
    '{0:.{1}}'.format(s, maxwidth)   #      
    #'Eric hurt the little'

    整数フォーマットの規則はコロンで始まり、その後はオプションの文字ペア--1つの充填文字、1つの整列文字(1つ=記号と数字の間で充填するために追加された)に従うことができ、その後はオプションの記号文字:+は必須出力記号を表し、-負の記号のみを出力し、スペースは正の出力スペースを表す.負の出力-です.次に続くのは、任意選択の最小幅整数値です.前に#ガイドを使用して、ある基数進数を接頭辞とする出力を取得するか、0ガイドを使用して、位置合わせ時に0で埋め込むことができます.他の進数のデータを出力するには、タイプ文字を追加する必要があります.type:
  • bバイナリ
  • o 8進
  • x小文字16進
  • X大文字16進
  • d十進法
  • c整数対応Unicode文字
  • nは、場所に敏感に出力する数字
  • を表す
    2つの異なる方法で0で充填
    '{0:0=12}'.format(7654321)
    #'000007654321'
    '{0:0=12}'.format(-7654321)
    #'-00007654321'
    '{0:012}'.format(7654321)
    #'000007654321'
    '{0:012}'.format(-7654321)
    #'-00007654321'
    '{0:0>12}'.format(-7654321)
    #'0000-7654321'

    インスタンスの整列
    '{0:*<15}'.format(123456789)
    #'123456789******'
    '{0:*>15}'.format(123456789)
    #'******123456789'
    '{0:*^15}'.format(123456789)
    #'***123456789***'
    '{0:*^15}'.format(123456789)
    '**-123456789***'
    '{0:*15}'.format(-123456789)
    #        0      =    
    '[{0: }] [{1: }]'.format(12345, -12345)  #space
    '[ 12345] [-12345]'
    '[{0:+}] [{1:+}]'.format(12345, -12345)# +
    '[+12345] [-12345]'
    '[{0:-}] [{1:-}]'.format(12345, -12345)#-
    '[12345] [-12345]'
    '{0:b} {0:o} {0:x} {0:X}'.format(12345678)
    #'101111000110000101001110 57060516 bc614e BC614E'
    '{0:#b} {0:#o} {0:#x} {0:#X}'.format(12345678)
    #'0b101111000110000101001110 0o57060516 0xbc614e 0XBC614E'

    整数の最大フィールド幅を指定することはできません.数値は切り取れません.フォーマット仕様に追加すると、整数が使用され、区切られます.
    '{0:,}  {0:*>13,}'.format(2.3242424e6)
    #'2,324,242.4  **2,324,242.4'

    nそれは場所によっていくつかの例に変わります.私もよく分かりませんから.
    import locale
    locale.setlocale(locale.LC_ALL, '')
    #'Chinese (Simplified)_China.936'
    x,y = (1234567890, 1234.56)
    locale.setlocale(locale.LC_ALL, 'C')
    #'C'
    c = '{0:n} {1:n}'.format(x, y)
    #'1234567890 1234.56'
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    #'en_US.UTF-8'
    en = '{0:n} {1:n}'.format(x, y)
    #'1,234,567,890 1,234.56'
    locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
    #'de_DE.UTF-8'
    de = '{0:n} {1:n}'.format(x, y)
    #'1.234.567.890 1.234,56'
    '{0:?

    $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\[$ ```python '{0:*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$浮動小数点以下で追従する数値を指定できます.末尾でも2つの差があります.任意の最小1つのタイプの文字を追加します:eは小文字eを使用する指数形式を表し、Eは大文字Eを使用する指数形式を表し、fは標準の浮動小数点形式を表し、gは「通常」の形式を表し、また%は、数字が100倍に拡大し、フォーマットがfで1%以上になります.
    '[{0:12.2e}] [{0:12.2f}] [{0:12.2E}]'.format(amount)
    #'[    3.14e+03] [     3141.59] [    3.14E+03]'
    '[{0:*>+12.2e}] [{0:*>+12.2f}] [{0:*>+12.2E}]'.format(amount)
    #'[***+3.14e+03] [****+3141.59] [***+3.14E+03]'
    '[{:,.6f}]'.format(decimal.Decimal('1234567890.1234567890'))
    #'[1,234,567,890.123457]'

    複数の場合、次の2つの方法があります.
    '{0.real:.3f}{0.imag:+.3f}j'.format(4.4342+14.2j)  #python3.0  
    #'4.434+14.200j'
    '{0:,.3f}'.format(4232.43323242+1323432.3232322j) #python3.1    float  
    #'4,232.433+1,323,432.323j'

    インスタンス1
    import sys, unicodedata
    
    
    def print_unicode_table(word):
        
        print('decimal    hex    chr    {0:^40}'.format('name'))
        print('-------    ---    ---    {0:-<40}'.format(''))
        
        code = 0
        end = sys.maxunicode
        
        while code < end:
            
            c = chr(code)
            
            name = unicodedata.name(c, '*** unknown ***')
            if word is None or word in name.lower():  #word in name.lower()  if word == None,        
                print('{0:7}    {0:5X}    {0:^3c}    {1}'.format(code, name.title()))
                
            code += 1
            
            
    
    word = None
    if len(sys.argv) > 1:        
        if sys.argv[1] in ('-h', '--help'):
            print('usage:{0} [string])'.format(sys.argv[0]))
            word = 0
        else:
            word = sys.argv[1].lower()
            
    if word != 0:
        print_unicode_table(word)

    例2
    import cmath
    import math
    import sys
    
    def get_float(msg, allow_zero):
    
        x = None
        while x is None:
    
            try:
                x = float(input(msg))
                if not allow_zero and abs(x) < sys.float_info.epsilon:
                    print('zero is not allowed')
                    x = None
    
            except ValueError as  err:
                print(err)
    
        return x
    
    print('ax\N{SUPERSCRIPT TWO} + bx + c = 0')
    a = get_float('enter a: ', False)
    b = get_float('enter b: ', True)
    c = get_float('enter c: ', True)
    
    x1 = None
    x2 = None
    discriminant = (b ** 2) - (4 * a * c)
    if discriminant == 0:
    
        x1 = -(b / (2 * a))
    else:
        if discriminant > 0:
            root = math.sqrt(discriminant)
        else:
            root = cmath.sqrt(discriminant)
        x1 = (-b + root) / (2 * a)
        x2 = (-b - root) / (2 * a)
    
    
    equation = ('{a}x\N{SUPERSCRIPT TWO} + {b}x + {c} = 0'
                '\N{RIGHTWARDS ARROW}x = {x1}').format(**locals())
    if x2 is not None:
        equation += 'or x = {}'.format(x2)
    
    print(equation)
    

    例3
    
    
    
    def print_start():
    
        print('')
    
    def extract_fields(line):
    
        fields = []
        field = ""
        quote = None
    
        for c in line:
            if c in "\"'":
                if quote is None:
                    quote = c
                elif quote == c:
                    quote = None
                else:
                    field += c
                continue
            if quote is None and c == ",":
                fields.append(field)
                field = ""
            else:
                field += c
    
        if field:
            fields.append(field)
    
        return fields
    
    
    
    
    def excape_html(text):
    
        text = text.replace("&", "&")
        text = text.replace("", ">")
    
        return text
    
    
    def print_line(line, color, maxwidth):
    
        print(''.format(color))
        fields = extract_fields(line)
    
        for field in fields:
            if not field:
                print('".format(round(x)))
                except ValueError:
                    field = field.title()
                    field = field.replace(' And ', ' and ')
                    if len(field) <= maxwidth:
                        field = excape_html(field)
                    else:
                        field = "{0} ...".format(excape_html(field[:maxwidth]))
    
                    print(''.format(field))
        print('')
    
    
    def print_end():
    
        print('
    ') else: number = field.replace(',', '') try: x = float(number) print("{0:d}{0}
    ') def main(): maxwidth = 100 print_start() count = 0 while True: try: line = input() if count == 0: color = 'lightgreen' elif count % 2: color = 'white' else: color = 'lightyellow' print_line(line, color, maxwidth) count += 1 except EOFError: break print_end() if __name__ == '__main__': main()

    練習する
  • import sys, unicodedata
    def print_unicode_table(word):
        
        print('decimal    hex    chr    {0:^40}'.format('name'))
        print('-------    ---    ---    {0:-<40}'.format(''))
        
        code = 0
        end = sys.maxunicode
        
        while code < end:
            
            c = chr(code)
            
            name = unicodedata.name(c, '*** unknown ***')
            if word is None or word in name.lower():  #word in name.lower()  if word == None,        
                print('{0:7}    {0:5X}    {0:^3c}    {1}'.format(code, name.title()))
                
            code += 1
    words = []
    while True:
        word = input('the unicodedata you need:')
        if word == '':
            break
        else:
            try:
                word = word.lower()
                words.append(word)
            except:
                print('can not lower')
    
    words = list(set(words))
    
    for word in words:
        if word in ('-h', '--help'):
            print('usage: {0} [string]'.format(sys.argv[0]))
        else:
            print_unicode_table(word)
    print('{0:-<40}  END  {0:->40}'.format(''))
  • def print_start():
    
        print('')
    
    def extract_fields(line):
    
        fields = []
        field = ""
        quote = None
    
        for c in line:
            if c in "\"'":
                if quote is None:
                    quote = c
                elif quote == c:
                    quote = None
                else:
                    field += c
                continue
            if quote is None and c == ",":
                fields.append(field)
                field = ""
            else:
                field += c
    
        if field:
            fields.append(field)
    
        return fields
    
    
    
    
    def excape_html(text):
    
        text = text.replace("&", "&")
        text = text.replace("", ">")
    
        return text
    
    
    def print_line(line, color, maxwidth, de_format):
    
        print(''.format(color))
        fields = extract_fields(line)
    
        for field in fields:
            if not field:
                print('".format(x, de_format))
                except ValueError:
                    field = field.title()
                    field = field.replace(' And ', ' and ')
                    if len(field) <= maxwidth:
                        field = excape_html(field)
                    else:
                        field = "{0} ...".format(excape_html(field[:maxwidth]))
    
                    print(''.format(field))
        print('')
    
    
    def print_end():
    
        print('
    ') else: number = field.replace(',', '') try: x = float(number) print("{0:{1}}{0}
    ') def process_options(): try: maxwidth = input('The maxwidth, defualt:100 :') de_format = input('The format, defualt:\'.0f\' :') maxwidth = int(maxwidth) except ValueError: maxwidth = 100 except EOFError: maxwidth = 100 de_format = '.0f' if len(sys.argv) > 1: if sys.argv[1] in ('-h', '--help'): print("usage:
    " "csv2html.py [maxwidth=int] [format=str] outfile.html
    " "

    " "maxwidth is an optional integer;if specified, it sets the maximum
    " "number of characters that can be output for string fields,
    " "otherwise a default of 100 characters is used.
    " "

    " "foramt is the format to use for numbers; if not specified it
    " "defaults to \".of\". ") return maxwidth, de_format def main(): maxwidth, de_format = process_options() print_start() count = 0 while True: try: line = input() if count == 0: color = 'lightgreen' elif count % 2: color = 'white' else: color = 'lightyellow' print_line(line, color, maxwidth, de_format) count += 1 except EOFError: break print_end() if __name__ == '__main__': main()

    転載先:https://www.cnblogs.com/MTandHJ/p/10528135.html