简体   繁体   English

如何从一个整数列表和一个布尔值列表创建一个列表? (Python)

[英]How do I create a list from one list of integers and one list of booleans? (Python)

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?我如何创建下面的列表(仅使用 list1 中按索引位置对应于 list2 中的 false 的项目?

list3 = [1,3,5,6]

Thanks谢谢

Use .zip使用.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]输出 [1, 3, 5, 6]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将一个列表中的所有整数添加到另一个列表中的整数,并在Python中以相同的顺序使用不同的长度? - How do I add all integers in one list to integers on another list with different length in the same order in Python? 如何从phython中给定的整数列表创建布尔的多列列表? - How to create multiple column list of booleans from given list of integers in phython? 如何返回布尔值列表以查看一个列表的元素是否在另一个列表中 - How to return list of booleans to see if elements of one list in another list 如何将整数列表加入一个整数python - How to join list of integers into one integer python 如何在 Python 中将一个列表中的整数添加到另一个列表中 - How to add the integers in one list to another in Python 如何创建一个返回从n到1的整数列表的函数? - How do I create a function that returns a list of integers from n to 1? 如何从Python列表中删除一个实例? - How do I remove only one instance from a list in Python? 如何使用python在另一个列表中找到一个列表? - How do i find one list in another list with python? 如何将多个整数作为一个输入的列表附加到列表中? - How to append multiple integers to a list as a list from one input? 遍历布尔值列表以创建新的整数列表 - Iterate through a list of booleans in order to create a new list of integers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM