How it works: print (sum (int (x) for x in raw_input (). Split ())) in Python

I am very new to Python and I am really surprised at the next line of code.

print (sum(int(x) for x in raw_input().split())) 

I cannot understand what is happening inside with my Java brain, especially since x is passed int () from the for loop.

+4
source share
6 answers

raw_input().split() returns an array for each input line. (int(x) for x in a) is a generator expression that applies an int to each line of input, converting it to an integer. The result of the generator expression is an array of integers; one for each line of input.

Finally, sum takes the sum of all the elements in the array, and, of course, print prints the entire batch. Thus, the result is code that produces the sum of all input lines, where each line is a number.

+7
source

First, raw_input().split() reads a string, which is then split into parts separated by spaces. Thus, a string of type 1 3 2 5 7 3 becomes a list ['1', '3', '2', '5', '7', '3'] .

This list is used in the expression int(x) for x in list_above . This expression is evaluated by a generator that converts list items to their int() views.

This generator is evaluated during the call to sum() , which sums all the numbers.

+1
source

Let's break it.

 print (sum(int(x) for x in raw_input().split())) 

Also expressed as

 sequence = raw_input().split() conv = [] for i in sequence: conv.append(int(i)) print sum(conv) 

Now we can combine this into one line using

 [int(x) for x in raw_input().split()] 

But this is not lazy. Therefore, to make it lazy, we simply replace [ with (

 (int(x) for x in raw_input().split()) 

Now, since this is an iterable object, we can pass this to sum()

And this is what happens.

+1
source

with this split() you break the numbers, so now you have a list.

you iterate over this list: for x in "list"

and you added this x to int: int(x)

all in one line of code

0
source

This is an expression of a generator. As a very rough approximation you can read it as

 a = [] for x in raw_input().split(): a.append(int(x)) print sum(a) 

but it does not create an interim list a .

0
source

The innermost part (int(x) for x in raw_input().split()) is a generator expression that works as follows:

 (and_evaluate_this for into,these,variables in unpack_this) 

Now delete the words "for" and "in", leaving:

 (and_evaluate_this into,these,variables unpack_this) 

And read from right to left . The sequence of evaluated expressions is generated by cyclizing these steps.

0
source

Source: https://habr.com/ru/post/1394808/


All Articles