How to print the progress of a list comprehension in python?

后端 未结 5 1407
忘掉有多难
忘掉有多难 2021-01-02 23:17

In my method i have to return a list within a list. I would like to have a list comprehension, because of the performance since the list takes about 5 minutes to create.

5条回答
  •  青春惊慌失措
    2021-01-02 23:33

    I have the need to make @ted's answer (imo) more readable and to add some explanations.

    Tidied up solution:

    # Function to print the index, if the index is evenly divisable by 1000:
    def report(index):
        if index % 1000 == 0:
            print(index)
    
    # The function the user wants to apply on the list elements
    def process(x, index, report):
         report(index) # Call of the reporting function
         return 'something ' + x # ! Just an example, replace with your desired application
    
    # !Just an example, replace with your list to iterate over
    mylist = ['number ' + str(k) for k in range(5000)]
    
    # Running a list comprehension
    [process(x, index, report) for index, x in enumerate(mylist)]
    

    Explanation: of enumerate(mylist): using the function enumerate it is possible to have indices in addition to the elements of an iterable object (cf. this question and its answers). For example

    [(index, x) for index, x in enumerate(["a", "b", "c"])] #returns
    [(0, 'a'), (1, 'b'), (2, 'c')]
    

    Note: index and x are no reserved names, just names I found convenient - [(foo, bar) for foo, bar in enumerate(["a", "b", "c"])] yields the same result.

提交回复
热议问题