How to add extra statements in a python list comprehension? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

How to add extra statements in a python list comprehension?

I wanted to find the highs and lows in a list which contains random data. This was the way I accomplished it.. https://code.sololearn.com/cxFtz17P4CDh/?ref=app While this works fine, I tried doing the same using list comprehension but to no avail, so how do I do that within the list comprehension?

21st Dec 2019, 4:45 PM
Moree
Moree - avatar
26 Answers
+ 7
The code is ok, but still missing the task description. Why this sequence of numbers as output?
21st Dec 2019, 5:43 PM
Lothar
Lothar - avatar
+ 6
I'm still not sure if this is what you want, since I have no idea about finance. :) If you need the indexes of the highest and lowest points and the info if they are high or low, I would do this: x = [4, 1, 5, 8, 4, 9, 3, 5, 9, 1, 7] hilo = [ ('high' if n==max(x) else 'low', i) for i, n in enumerate(x) if n==max(x) or n==min(x) ]
22nd Dec 2019, 7:14 AM
HonFu
HonFu - avatar
+ 4
There is a max and min function...but...as you've used the term "highest and lowest" I assume you need to return all the values higher than a pre-defined value and values lower than that pre-defined value. Give a sample input and expected output. I don''t understand how the output of your prog does what your post is asking to do.
21st Dec 2019, 5:09 PM
rodwynnejones
rodwynnejones - avatar
+ 4
I fully agree with rodwynnejones, we need a clear description what to do so that we can help.
21st Dec 2019, 5:29 PM
Lothar
Lothar - avatar
+ 4
Hm... not really sure what you're aiming to do... Can you maybe give a simple series of inputs and outputs to illustrate?
21st Dec 2019, 8:17 PM
HonFu
HonFu - avatar
+ 4
Well still not quite clear for me, what is your criteria for the output, but here is my two cents. You seem to be building two lists, one for the high values and the other for the low values. The way I see it, if we look for local peaks then we need to compare 3 adjacent values (a, b, c) and we have a peak at b when a<b>c Hence my idea is to use the zip function. Same logic with local lows. The first and last value in the series wouldn't be considered in either group (but this should not matter in a longer series). One more idea to improve this, is to also store the index (timestamp or x axis) of the datapoint, instead of just the value. You can use the enumerate function for this and change the list comprehension into a dict comprehension, with the timestamp as key. Another undefined case, when two consecutive values are equal. (is that a high or low or neither...) https://code.sololearn.com/cGpaHFSjbO1a/?ref=app
21st Dec 2019, 10:43 PM
Tibor Santa
Tibor Santa - avatar
+ 3
For me this is still a lack of information comparing the input to the output values. There are 14 input values and 7 output values. This needs more and precice definition and information.
21st Dec 2019, 8:16 PM
Lothar
Lothar - avatar
+ 3
Tibor Santa Excellent!, this is exactly what I wanted, but the first and last values ​​are very important and should not be ignored, as there are decisions that depend on those values. If there are two consecutive equal values, they will be considered as one value.
22nd Dec 2019, 9:40 AM
Moree
Moree - avatar
+ 3
Mohamed Khalaf ultimately, list comprehensions are not always the best solution to all problems. When dealing with long series, the itertools library is always worth checking, it has a ton of utility functions to handle iterators (lazy sequences). Also the pandas library has neat tricks for statistical analysis. In the meantime I had some other ideas for your problem, for example to visualize the direction of the trend between two datapoints, and using itertools.groupby() to determine the local peaks and lows precisely. See my code for more details. https://code.sololearn.com/crZuWRjf3c9x/?ref=app
22nd Dec 2019, 6:07 PM
Tibor Santa
Tibor Santa - avatar
+ 2
Still don't get it...your function (upLo(input)) returns a tuple which is then unpacked into "H" and "L" but your output is a list. I cant see how you output relates to your input.
21st Dec 2019, 6:14 PM
rodwynnejones
rodwynnejones - avatar
+ 2
By using functions you can have as many statements as you need: def f(x): if x % 2 == 0 and x % 3 == 0: return "Divisible by 2 and 3." elif x % 3 == 0: return "Divisible by 3." elif x % 2 == 0: return "Divisible by 2." else: return "Not divisible by 2 or 3." [f(i) for i in range(10)] But if you are one-liner you can use list comprehensions, but you can't use non-evaluating statements: ["Divisible by 2 and 3." if i % 2 == 0 and i % 3 == 0 else ("Divisible by 3." if i % 3 == 0 else ("Divisible by 2." if i % 2 == 0 else "Not divisible by 2 or 3.")) for i in range(10)]
21st Dec 2019, 6:27 PM
Seb TheS
Seb TheS - avatar
+ 2
Tibor Santa I actually use the pandas library in my daily work but I wanted to do that away from the libraries in order to reach a deeper understanding. I am very thankful to you for your interest and effort. 😊
24th Dec 2019, 10:03 PM
Moree
Moree - avatar
+ 1
Maybe you find here what you need? https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app
21st Dec 2019, 6:13 PM
HonFu
HonFu - avatar
+ 1
Lothar This is a job for time series analysis to find where are highs and lows in the entire sequence. basically as you iterate through the data if you go from ascending to descending you have a (high), and from descending to ascending you have a (low). I hope that you would understand.
21st Dec 2019, 7:35 PM
Moree
Moree - avatar
+ 1
Lothar HonFu In order, where is the lowest and highest number in this list [1, 3]? There is no doubt that No. 1 is the lowest and No. 3 is the highest. What would happen if there were a lot of random numbers, e.g. [1, 2, 3, 2, 1]? By the same logic, the result will be.. Low >>> 1 High >>> 3 Low >>> 1 This concept is widely used in analyzing financial markets
21st Dec 2019, 10:21 PM
Moree
Moree - avatar
+ 1
HonFu I appreciate your efforts to help me, but it's okay. Thank you anyway 🙏😊
22nd Dec 2019, 9:52 AM
Moree
Moree - avatar
0
input = [9, 8, 7, 6, 1, 2, 3, 4, 5, 3, 6, 8, 17, 20] def upLo(input): pre, top, low, era = input[0], [], [], None # I want to do that using list comprehension..👇 for val in input[1:]: if not era and val > pre: era = 1 low.append(pre) elif (era is None or era) and val < pre: era = 0 top.append(pre) pre = val if era: top.append(input[-1]) else: low.append(input[-1]) return top , low print(upLo(data)) 👇 Expected output: ([9, 5, 8, 20], [1,3,7])
21st Dec 2019, 5:31 PM
Moree
Moree - avatar
0
HonFu Sorry, there was a typing error, and I edited my comment.
21st Dec 2019, 7:49 PM
Moree
Moree - avatar
0
Lothar I have a loop that contains more than one statement that I want to convert into list comprehension. In another words, I just want to learn how we can write complex for statements into a single line.
21st Dec 2019, 10:07 PM
Moree
Moree - avatar
0
Am a beginner, how will i start?
23rd Dec 2019, 1:31 AM
Matthew Ochiwu
Matthew Ochiwu - avatar