using functions to display numbers in a list

后端 未结 4 1086
面向向阳花
面向向阳花 2021-01-29 14:09

I have a list of numbers and I have to use a function to display them in celsius, they are in fahrenheit now.

nums = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,         


        
相关标签:
4条回答
  • 2021-01-29 14:25
    print ','.join([str(fahrenToCel(fahren)) for fahren in nums])
    

    This will not only create a new list, but will also join it as a comma-separated string.

    If nums is rather long, you can save some memory and performance by using a generator expression instead of list comprehension. You just have to take off the square brackets:

    print ','.join(str(fahrenToCel(fahren)) for fahren in nums)
    
    0 讨论(0)
  • 2021-01-29 14:27

    Your function seems to take as input a single number, yet you're giving it a list of numbers. If you want to generate a list of converted numbers using that function, you can use list comprehension:

    cels = [fahrenToCel(fah) for fah in nums]
    
    0 讨论(0)
  • 2021-01-29 14:31

    If you have a list the_list and you want to apply a function f to each element, creating a new list of the results:

    new_list = [f(x) for x in the_list]
    
    0 讨论(0)
  • 2021-01-29 14:47

    The simplest way would be to use a for loop to iterate over the list and printing each result:

    #!/usr/bin/env python
    
    # def farentoCel(x): ...
    # ...
    
    if __name__ == '__main__':
        import sys
    
        for each_num in sys.argv[1:]:
            print farentoCel(int(each_num))
    

    As others have said you can replace this explicit loop with a list comprehension (expression), or even a generator comprehension (in newer versions of Python).

    In this case I'm showing a very simple skeleton for you to use for testing simple functions. The if _ name _ == '_ main _': suite is a Python convention used to separate your function, class, and other definitions from the run-time of your code. This can be used to structure your code so that it can be re-used in (imported into) other code while also exposing some functionality in a command line utility (wrapper) or providing a default interface (perhaps a GUI).

    In the fairly common case where your module doesn't have simply accessible utility (where it's only useful when incorporated into other code) then you can use the '_ main _' suite to contain unit test cases.

    0 讨论(0)
提交回复
热议问题