H
H
Helper2021-10-03 16:15:32
Python
Helper, 2021-10-03 16:15:32

Can you explain how it works?

Code:
value = list(map(int, input().split())) (I understand this)
value_mid = sum(value:=value[:[i for i in range(len(value)) if value[i ] < 0][0]]) /len(value)

I understand everything, except for the line [:[i for i in range(len(value)) if value[i] < 0[0]]). Explain, please, very clearly what and how it does. And, preferably, write an equivalent. I'm more tormented by this [0] after the condition. Thanks to everyone who helped!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-10-03
@Vadim200102

Tin. Let's expand it from outside to inside:

value_mid = sum(
    value:=value[
        :[
            i for i in range(len(value)) if value[i] < 0
        ][0]
    ]
 ) /len(value)

Outside, the sum of some series of numbers (not entered) divided by the number.
Next comes the assignment inside the expression (one of the new python tricks, in fact value is redefined.
As a result, len(value) will already contain the number of elements in the new value, and not in the original one.
Next comes the value[:X] slice, that is, from X is [i for i in range( len
(value)) if value[i] < 0][0], i.e. the null element of the list given by
[i for i in range(len (value)) if value[i] < 0] This expression will contain the indices of all negative elements of value, so X will contain the index of the first negative element of value.
Then the sum will be counted from the beginning of the list to the first negative element (not including), and the quantity will also be counted in the same way.
Conclusion: The expression counts the average of the elements of the list from the beginning to the first negative element, and it does this through an extremely tricky ass.

D
dmshar, 2021-10-03
@dmshar

Actually, you have written two different things:
first:

value[:[i for i in range(len(value)) if value[i] < 0][0]])

after:
[:[i for i in range(len(value)) if value[i] < 0[0]])

Doesn't this "torment" you, or is it on purpose to confuse everyone?
According to the first version of the notation , "[0] after the condition" means the desire of the code author to take the first element of the list, which is generated here: and in which the elements of the list less than 0 are selected. Accordingly,
[i for i in range(len(value)) if value[i] < 0]
value[:[i for i in range(len(value)) if value[i] < 0][0]]

selection of elements of this list, going up to the first negative element of the list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question