A python question previously asked by a colleague

Source: Internet
Author: User

Python face question

Previous colleague asked a Python topic as follows, temporarily categorized as a face question

Title: Put similar‘123.456‘string into floating-point data
    • Method One:

        print ‘{:.3f}‘.format(float(‘123.456‘))  >>> 123.456
    • Method Two: Specifying map , reduce higher order functions

      Idea: The decimal point is processed first, and then the integer digits and decimal places are added. Steps are as follows

      s = ‘123.456‘

  1. Working with decimals: Use a string slice method.

    s.split(‘.‘)

    This gives you 2 an array of length[‘123‘, ‘456‘]

  2. Processes the first element in the list (an integer column). Use an iterative approach to get integers123

    def map_int(s):     ‘‘‘ @see: 迭代时把字符串转换成int类型 ‘‘‘ return int(s)

    Then use the higher map(func, seq) -order function to iterate over the string in the list: get[1, 2, 3]

     map(map_int, s.split(‘.‘)[0])
  3. Uses higher-order functions Reduce (func, seq) to accumulate data after map () 123

     Reduce (lambda x, y: x*10 + y, map (map_int, S.split ('. ') [0]))  
    " > reduce (lambda x,y:x*10 + y, map (Map_int, S.split (". [0]))

    The same method handles decimal digits

     Reduce (lambda x, y: x*0.1 + y, map (map_int, S.split ('. ') [1] [::-1])) * 0.1  
    "> reduce (lambda x,y:x*0.1 + y, map (Map_int, S.split ( ") [1][::-< span class= "Hljs-number" >1])) * 0.1
  • The entire code block is as follows: or simply replace the Map_int () function with the following: Lambda X:int (x)

      def Map_int(s): "@see: Convert a string to int type ' return int (s) reduce (lambda x,y:x*+ y) at iteration Map (Map_int, S.split ('. ') [0]) + reduce (lambda x,y:x*0.1 + y, map (Map_int, S.split ('. ') [1][::-1]) * 0.1              

Generated by Haroopad

A python question previously asked by a colleague

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.