简体   繁体   中英

Fastest way to calculate new list from empty list in python

I want to perform calculations on a list and assign this to a second list, but I want to do this in the most efficient way possible as I'll be using a lot of data. What is the best way to do this? My current version uses append:

f=time_series_data
output=[]
for i, f in enumerate(time_series_data):
    if f > x:
        output.append(calculation with f)
          etc etc

should I use append or declare the output list as a list of zeros at the beginning?

Appending the values is not slower compared to other ways possible to accomplish this.

The code looks fine and creating a list of zeroes would not help any further. Although it can create problems as you might not know how many values will pass the condition f > x .

Since you wrote etc etc I am not sure how long or what operations you need to do there. If possible try using list comprehension. That would be a little faster.

You can have a look at below article which compared the speed for list creation using 3 methods, viz, list comprehension , append , pre-initialization .

https://levelup.gitconnected.com/faster-lists-in-python-4c4287502f0a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM