What is the meaning of the following line of code?
arr = [a+b for a,b in list]
Usually the for loop is used with one variable (in this case, the i)
arr = [i for i in list]
In the first case, the for loop uses several variables "a" and "b", which I cannot understand. Please explain this format.
This is called unpacking. If the list (or any other iterable) contains two-element iterations, they can be unpacked, so individual elements can be accessed like aand b.
a
b
For example, if it listwas defined as
list
list = [(1, 2), (3, 4), (4, 6)]
your end result will be
arr = [3, 7, 10]
, , , . , , ( , ).
(, ) enumerate, , . - :
enumerate
arr = [ind + item for ind, item in enumerate(numbers)]
for a,b in list ( ). , list [(a0, b0), (a1, b1), ...].
for a,b in list
[(a0, b0), (a1, b1), ...]
, [a+b for a,b in list] [a0+b0, a1+b1, ...].
[a+b for a,b in list]
[a0+b0, a1+b1, ...]
list / 2 , ,
a,b in x
, a b
>>> a,b = [1, 2] >>> a 1 >>> b 2
>>> x = [ (i, i*i) for i in range(5) ] >>> x [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)] >>> [ a+b for a,b in x ] [0, 2, 6, 12, 20]
What happens is called tuple unpacking. Each element in listmust be a tuple or some other equivalent type of sequence that can be unpacked.
Example:
l = [(1, 2), (3, 4)] arr = [a + b for a, b in l] print(arr)
Conclusion:
[3, 7] # [(1+2), (3+4)]
Source: https://habr.com/ru/post/1666577/More articles:https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1666572/how-to-go-for-refresh-token-automatically-when-access-token-expired-and-get-401-using-httpurlconnection-in-android&usg=ALkJrhiZsWQrH8Y_f0otbE5O3qmgSU7qhAScrollTop not working in React component or inspector - javascriptAndroid TextView Marquee not working - androidTextView Marquee not working - androidThe Azure AD API returns System.Security.Principal.GenericIdentity.IsAuthenticated as false always - c #Error executing git command because stCommitMsg file was not found - gitTextView with highlighted area not working - androidNo content to display due to nested plugin - javaRxjava2 + Retrofit2 + Android. The best way to make hundreds of network calls - javaInclude HTML markup file content for remark.js - htmlAll Articles