Issue
I am faced issue with a list comprehension missing value in a result list. I have two lists. when i am trying with for loop. value is expected as i want to like(7 4 2 -1 0) but i don't need integer values in need list. when use list comprehension i got only 4 value [4, 2, -1, 0]. i don't understand what happens in my logic. if there is anyone you help me kindly see a code.
l1 = [3, 6, 9, 2, 11, 14, 13]
f = [7]
subtraction l1 last element to l1 nth element. I am trying this formula(pls see code more understandable):
l2 = l1[-1]-l1[n]
and after that, i am trying to put if else condition in like this:
if l2 <= f:
print(l3)
this is the code I am trying in for loop
In [230]: for l2 in l1:
...: l3 = l1[-1]-l2
...: #print(l3)
...: for f1 in f:
...: if l3<=f1:
...: print(l3)
...:
...:
7
4
2
-1
0
And for the List Comprehension code is:
for f1 in f:
f1
In [47]: l1 = [x[-1] - l for l in x if l >= int(f1)]
...:
In [48]: l1
Out[48]: [4, 2, -1, 0]
Solution
Your list comprehension does not match with your for
loop.
You must replace:
[x[-1] - l for l in x if l >= int(f1)]
with:
[(l1[-1] - l) for l in l1 if (l1[-1] - l) <= int(f1)]
which gives the expected output.
(I added parentheses for better readability)
Answered By - Laurent H.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.