4

Here is my code :

evenorodd=[1,2,3]
list1=['a','b','c']
list2=['A','B','C']

res = tuple(map(lambda x: True if x % 2 != 0 else False, evenorodd))

print(res)

the output:

(False, True, False, True)

I want this : element of list1 if x%2!=0 (if element of evenorodd is odd) element of list2 else (if element of evenorodd is even) The output that I look for:

('a','B','c')

and I want to do that on one line

res = tuple(map(lambda x: ??? if x % 2 != 0 else ???, evenorodd))

Thank you

AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
bryan tetris
  • 123
  • 1
  • 3
  • 7

4 Answers4

4

You can use zip:

evenorodd=[1,2,3]
list1=['a','b','c']
list2=['A','B','C']
new_result = [a if c%2 == 0 else b for a, b, c in zip(list2, list1, evenorodd)]

Output:

['a', 'B', 'c']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • @AntonvBR Not exactly. I think it is important to retain the OP's original `evenorodd` structure. For instance, What if the input is`[1,3,6,7]`, `['a','b','c','d']`, `['A','B','C','D']`? – Ajax1234 May 18 '18 at 23:20
  • @AntonvBR But to be fair, it is merely an assumption. I will delete my post if you think it too closely emulates yours. – Ajax1234 May 18 '18 at 23:23
  • It's ok. I was having a conversation with OP in comments trying to understand what he really wanted. – Anton vBR May 18 '18 at 23:27
  • 1
    @bryantetris If you want to store a third array you might aswell make it boolean like [True, False, True] and use a "tripple zip" like Ajax1234 here proposes. If you want to use the index I'd suggest my solution with enumerate. In any case you might accept the one that suits your needs. – Anton vBR May 18 '18 at 23:44
3

Something like this:

res = tuple([x if not ind % 2 else y for ind, (x,y) in enumerate(zip(list1,list2))])
print(res)
#('a', 'B', 'c')
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
1

Another approach is to use numpy.where():

import numpy as np
tuple(np.where([i%2 for i in evenorodd], list1, list2))
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
1

Here is a solution that uses map and lambda-function exclusively:

tuple(map(lambda v: v[0] if v[2] % 2 else v[1], zip(list1, list2, evenorodd)))
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45