以下是给定值:
v = 1, w = 1, x = 1, y = 0, z = 1
j = 0, k = 1, l = 0, m = 0, n = 0, o = 0, p = 0
chked = [v, w, x, y, z]
unchked = [j, k, l, m, n, o, p]
我想做的是这样的事情:
for a in chked:
if a != 1
or
for b in unchked:
if b != 0:
Then only Do something. (change those element's value etc.)
答案 0 :(得分:2)
既然你想要做的事情是模糊的,我将不得不做出一些假设。如果你正在处理值限制为1s和0s的数组,并且当你不应该有1s或0时你想要“做某事”,你可以这样做:
v, w, x, y, z = 1, 1, 1, 0, 1
j, k, l, m, n, o, p = 0, 1, 0, 0, 0, 0, 0
# I assume you have reasons for storing each value separately from the list
chked = [v, w, x, y, z]
unchked = [j, k, l, m, n, o, p]
if not all(chked) or any(unchked):
DoSomething()
not all(chked)
将检查是否所有元素都是1。也就是说,chked中存在一些0。
虽然any(unchcked)
会检查0中是否存在1
。
但是,如果你想对不同的元素做点什么, 你可以这样做:
new_chcked = [DoSomethingOnA(a) if a == 0 else a for a in chcked]
new_unchcked = [DoSomethingOnB(b) if b == 1 else b for b in unchcked]
答案 1 :(得分:1)
您应该使用comprehension list
,如下所示:
if not [elt for elt in chked if elt == 0]
or not [elt for elt in unchked if elt == 1]):
#do stuff
答案 2 :(得分:1)
您想找到满足条件的所有元素吗?
a in range(len(chked))
或者你有两个相同长度的列表,并且想要搜索对(这是你在ng-class
的评论中所写的内容,但它不适合问题示例)
答案 3 :(得分:0)
正如我理解您的问题,您可能想要找到违反每个已检查/未检查对的规则的位置。 然后你可以使用以下代码:
# Example
chked = [1, 1, 1, 1]
unchked = [0, 0, 0, 1]
for a in range(len(chked)):
if chked[a] != 1 or unchked[a] != 0:
print "At index {0}: chked[{0}] = {1} \
and unchcked[{0}] = {2}".format(a, chked[a], unchked[a])