0

I want to convert this loop to a list comprehension but I'm stuck (A,B,C and D) are lists:

x = 0
for i in A:
  if i in B:
    if C[x] == D[x]:
       x = x + 1

This is what I have so far:

[if i in A for i in B]

Not sure where to go from here. Any help will be appreciated.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
magicsword
  • 1,179
  • 3
  • 16
  • 26
  • 2
    `if i in B: if C[x] == D[x]` is the same as `if (i in B) and (C[x] == D[x])`. – Carcigenicate Sep 02 '19 at 00:12
  • You can simplify that if statement so that you don't need multiple conditionals. But I'm not sure how you plan to deal with `x` being required to access the elements of `C` and `D`... I don't suppose that's a typo and you meant `i`? – Shadow Sep 02 '19 at 00:23
  • 3
    You aren't building a list, so a list comprehension isn't appropriate. – chepner Sep 02 '19 at 00:36
  • Your original loop doesn't seem to use `i`, is that intentional? Are `C`, `D` or `x` actually expressions that contain `i`? – Weeble Sep 02 '19 at 00:41
  • Can you explain what this is supposed to do? Because it looks pretty weird. If I read this correctly, `x` would end up the first index where `C` and `D` differ, but at most the number of common elements in `A` and `B`, is this what it's intended to do? – tobias_k Sep 02 '19 at 07:56

2 Answers2

0

You could do

sum([C[x] == D[x] for x in A if x in B])

This will implicitly convert Trues to 1 and Falses to 0.

Word of caution: You are trying to produce a single value out of this (aka reduce). List comprehensions are ideally for creating lists (map). Complex list comprehensions can be less readable.

I think this one maybe passes, but it's a little weird to do a sum over booleans.


Edit: As a comment pointed out, I assumed you actually meant to use the keys of A and B to index C and D, not the counter variable x in your original code snippet.

jagthebeetle
  • 705
  • 6
  • 11
0

I think you need this:-

A = [1,2,3]
B = [4,1,6]
C = [7,8,9]
D = [7,4,1]
x = 0

[i for i in A if (i in B) and (C[x]==D[x]) ]

Output

[1]
Rahul charan
  • 765
  • 7
  • 15