【发布时间】:2018-05-19 13:32:22
【问题描述】:
我需要做什么操作才能始终让 False 值变为 True 或让 True 值变为 False? 换句话说,我该怎么做才能切换给定变量的布尔值?
new_dict = {}
for i in range(1, 101):
new_dict[i] = False
i = 2
while i < 101:
for x in range(1, 101):
if new_dict[x] % i == 0:
a = new_dict[x]
new_dict[x] = not a
i += 1
for a in new_dict:
print 'Light #%d --> %r' % (a, new_dict[a])
下面的输出只有 True。由此,我了解到我出于某种原因所做的并不是将所有其他值都更改为 False。为什么会这样?
有人知道为什么吗?
Light #1 --> True
Light #2 --> True
Light #3 --> True
Light #4 --> True
Light #5 --> True
Light #6 --> True
Light #7 --> True
Light #8 --> True
Light #9 --> True
Light #10 --> True
Light #11 --> True
Light #12 --> True
Light #13 --> True
Light #14 --> True
Light #15 --> True
Light #16 --> True
Light #17 --> True
Light #18 --> True
Light #19 --> True
Light #20 --> True
Light #21 --> True
Light #22 --> True
Light #23 --> True
Light #24 --> True
Light #25 --> True
Light #26 --> True
Light #27 --> True
Light #28 --> True
Light #29 --> True
Light #30 --> True
Light #31 --> True
Light #32 --> True
Light #33 --> True
Light #34 --> True
Light #35 --> True
Light #36 --> True
Light #37 --> True
Light #38 --> True
Light #39 --> True
Light #40 --> True
Light #41 --> True
Light #42 --> True
Light #43 --> True
Light #44 --> True
Light #45 --> True
Light #46 --> True
Light #47 --> True
Light #48 --> True
Light #49 --> True
Light #50 --> True
Light #51 --> True
Light #52 --> True
Light #53 --> True
Light #54 --> True
Light #55 --> True
Light #56 --> True
Light #57 --> True
Light #58 --> True
Light #59 --> True
Light #60 --> True
Light #61 --> True
Light #62 --> True
Light #63 --> True
Light #64 --> True
Light #65 --> True
Light #66 --> True
Light #67 --> True
Light #68 --> True
Light #69 --> True
Light #70 --> True
Light #71 --> True
Light #72 --> True
Light #73 --> True
Light #74 --> True
Light #75 --> True
Light #76 --> True
Light #77 --> True
Light #78 --> True
Light #79 --> True
Light #80 --> True
Light #81 --> True
Light #82 --> True
Light #83 --> True
Light #84 --> True
Light #85 --> True
Light #86 --> True
Light #87 --> True
Light #88 --> True
Light #89 --> True
Light #90 --> True
Light #91 --> True
Light #92 --> True
Light #93 --> True
Light #94 --> True
Light #95 --> True
Light #96 --> True
Light #97 --> True
Light #98 --> True
Light #99 --> True
Light #100 --> True
How do I get the opposite (negation) of a Boolean in Python? 和python how to "negate" value : if true return false, if false return true 的问题似乎相同,但在我的情况下,这个简单的概念根本行不通......
谢谢,真的很感谢大家的帮助!!!
【问题讨论】:
-
逻辑非?您只想切换一个布尔值?
-
不确定这是否会被认为是一个简单的错字,但我很确定您正在寻找的答案是:用 x % 替换 new_dict[x] % i == 0 i == 0 在您的情况下...问题是 False % 2 (或任何数字)为 0 而 True % 数字为 1。我对此不太满意,但最终效果是第一次通过,您将所有内容设置为 True ,然后永远不要更改它......如果您按照您几乎可以肯定的意图进行操作并检查索引与值,它会按照我认为您的预期工作,或者至少给出 False 和 True 值的混合
-
if x % i == 0: new_dict[x] = not new_dict[x]您正在请求对布尔值进行模块操作,该值并不总是定义。