我有列表或/和元组:
MyVar = [0,0,0,0,1,0,0,0,0]
我想计算与0
不同的元素。
怎么做?
答案 0 :(得分:9)
无需生成列表,只需:
len(MyVar) - MyVar.count(0)
答案 1 :(得分:3)
获取非0
的所有元素的子列表的长度MyVar = [0,0,0,0,1,0,0,0,0]
len([x for x in MyVar if x != 0])
>> 1
答案 2 :(得分:2)
你可以尝试:
>>> len(filter(lambda x: x != 0, MyVar))
1
答案 3 :(得分:2)
以下内容应该有效:
>>> MyVar = [0,0,0,0,1,0,0,0,0]
>>> sum(map(bool, MyVar))
1
它会将列表转换为布尔值列表,如果元素为非零,则值为True
。然后通过隐式考虑值{1 True
和值{0 False
来对所有元素求和。
答案 4 :(得分:1)
尝试filter()
:
>>> my_var = [0, 0, 0, 0, 1, 0, 0, 0, 0]
>>> result = filter(lambda x: x > 0, my_var)
[1]
>>> print(len(result))
1
答案 5 :(得分:1)
您可以对条件生成器表达式执行$('document').ready(function()
{
/* validation */
$("#register-form").validate({
rules:
{
full_name: {
required: true,
minlength: 3
},
user_name: {
required: true,
minlength: 3
},
},
messages:
{
full_name: "please enter your full name",
user_name:{
required: "please enter your username",
minlength: "username must be more than than 3 characters"
},
},
submitHandler: submitForm
});
,该表达式不需要任何中间列表或不必要的算术运算:
sum
或者@ Jean-FrançoisFabre指出:
>>> sum(1 for element in MyVar if element != 0)
1
如果>>> sum(1 for element in MyVar if element)
1
仅包含数字,则会计算非零值的数量。
答案 6 :(得分:0)
不如上述任何答案效率高,但仍然简单直接
myVar = [0,0,0,0,1,0,0,0,0]
count = 0
for var in myVar:
if var != 0:
count += 1
答案 7 :(得分:0)
来自functools的reduce:
from functools import reduce
reduce((lambda x, y: x + (y>0)), MyVar, 0)
答案 8 :(得分:0)
f = sum([1 for x in MyVar if x!= 0])
一行:)
答案 9 :(得分:0)
使用迭代器之和:
sum(x != 0 for x in MyVar)