我试图划分列表的每个元素,看看列表中的数字是否返回偶数。我想要的是将 list_accepted_ant
中的偶数值附加到 set_accepted_list。目前,当我打印该值时,所有值都会附加到 set_accepted_list
中。任何帮助将不胜感激。
def DoIOpenTheDoor(list_ant_id):
list_accepted_ant = []
set_accepted_list = set()
set_forbidden_list = set()
set_list_ant_id = set(list_ant_id)
if len(list_accepted_ant) < num_accepted:
if len(list_ant_id) > 0:
list_accepted_ant.extend(list_ant_id[0:min(len(list_ant_id))
if (all(x % 2 == 0 for x in list_accepted_ant)):
list_accepted_ant.append(list_accepted_ant)
set_accepted_list = set(list_accepted_ant)
print "the set of even accepted ant-",(set_accepted_list)
print "the list of all ants-",(list_ant_id)
set_forbidden_list = set_list_ant_id-set_accepted_list
return set_accepted_list,set_list_ant_id,set_forbidden_list
这是我运行代码时的输出:
list_ant_id = [1082, 1091, 1055, 1057, 971, 977, 728, 740]
set_accepted_list = set([1057, 1091, 740, 971, 977, 728, 1082, 1055])
我的预期set_accepted_list = set([740,728,1082])
本质上,我想要的是将 list_ant_id 中的偶数值保留到 set_accepted_list 中。
最佳答案
问题是您正在尝试将 list_accepted_ant 中 x 的可迭代 x/2
与数字 0
进行比较,因此请更改:
([x/2 for x in list_accepted_ant ==0]): #for even number ants
到
all(x % 2 == 0 for x in list_accepted_ant))
上一行基本上是说,对于 list_accepted_ant
的每个元素,检查它们是否都是偶数。
关于python - 如何将整个列表的每个元素除以一个常数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45617364/