eg suppose I have two lists:
list1 = [1,2,3,4,5,6]
list2 = [False,True,False,True,False,False]
How can i create the list below (only using items in list1 that correspond to false in list2 by index position?
list3 = [1,3,5,6]
Thanks
Use .zip
list1 = [1,2,3,4,5,6]
list2 = [False,True,False,True,False,False]
list3=[j for i,j in zip(list2,list1) if i==False]
print(list3)
list1 = [1,2,3,4,5,6]
list2 = [False,True,False,True,False,False]
list3=[]
for i in range(0,len(list1)):
if list2[i] == False:
list3.append(list1[i])
Just use Boolean Logic and list comprehensions:
list1 = [1,2,3,4,5,6]
list2 = [False,True,False,True,False,False]
print([i[0] for i in zip(list1,list2) if not i[1]]) # this just includes an element if that element's corresponding value in the second list is False
This outputs:
[1, 3, 5, 6]
list1 = [1,2,3,4,5,6]
list2 = [False,True,False,True,False,False]
list3=[]
for i in range(len(list1)):
if list2[i]==False:
list3.append(list1[i])
list1 = [1,2,3,4,5,6]
list2 = [False,True,False,True,False,False]
output = list (map (lambda x,y: x if y == False else '', list1,list2))
while '' in output:
output.remove('')
print(output)
Outputs [1, 3, 5, 6]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.