0

I have a list : list_data = [1,2,3,4,5,6,7,8].

I want to find nested lists that will group continuous value if it has the number of standard deviations <= a specific number. Expect results (a specific number is 2): list_data = [[1,2,3,4,5,6],[7,8]].

Can I do that with list comprehension?

I have tried:

import statistics
list_data = [1,2,3,4,5,6,7,8]
results = [list(g) for key,[*g] in groupby(list1) if statistics.stdev(list(g)) <=2]

But maybe groupby can group the same value in the list so it's not working.

My question is can I do that with Python List comprehension or another solution with the best performance?

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • Not sure I understood 100% - but you may need to create all nested lists first [ [1,2], [ 1,2,3], ..., [1,2,3,4,5,6,7,8], [2],[2,3] , ... , [6,7,8], [7,8]] and then groupby their deviation and then select all that have a groupkey less then f.e. 2. IF you are sure what to do you can then try to fit it into a list comp - but it may be much clearer to not do it. – Patrick Artner Aug 30 '21 at 08:04
  • This might help you: https://stackoverflow.com/questions/1174984/how-to-efficiently-calculate-a-running-standard-deviation – user2390182 Aug 30 '21 at 08:05
  • `Python List comprehension` is not about performance. It is about writing shorter code. – balderman Aug 30 '21 at 08:08
  • hi @PatrickArtner, I can use `loop` to do that, but I think it's very slow than `list comprehension` – Toan Nguyen Phuoc Aug 30 '21 at 08:13
  • hi @balderman, I agree with you, but I think the performance of `list comprehension` is better than `loop`, is it? I can use `loop` to solve my problem (like Patrick Artner) but I find the best solution is faster and short. – Toan Nguyen Phuoc Aug 30 '21 at 08:15

0 Answers0