python - 如何将整个列表的每个元素除以一个常数

标签 python list function set

我试图划分列表的每个元素,看看列表中的数字是否返回偶数。我想要的是将 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/

相关文章:

C++ - 没有匹配的构造函数

Python For 循环、函数问题

javascript - Selenium 不会点击最上面的元素

query-performance - 如何使用 SQLAlchemy 和 PostgreSQL 对大表中的所有行进行有效排序?

python - Tensorflow Saver.save无法写入Docker共享卷

python - 有效地比较任意分配的标签列表

python - 列表返回的值比预期多

javascript - 我们可以使用相同的按钮来隐藏/显示多个 div

javascript - 在javascript中转换对象类型?

c++ - Boost-python 如何将 C++ 类实例传递给 Python 类