Python 运行一个不应该运行的 if-case!
我有这样的代码:
def random_answerlist(self):
self.li = []
self.winning_button = random.randint(0, 3)
i = 0
while i < 20 and len(self.li) is not 4:
if i == self.winning_button:
self.li.append(self.flags[self.current_flag][0])
else:
new_value = self.random_value()
if self.flags[new_value][0] not in self.li:
self.li.append(self.flags[new_value][0])
i += 1
return self.li
它的唯一问题是第一个 if-case 可能会发生几次,这应该是不可能的。我已经为此寻找了一个很好的解释,但找不到任何解释。
哦,我知道代码不是最好的。但我对 python 有点陌生(只有一个月左右),认为这可能有效,但事实并非如此!
你们知道为什么吗? =)
I have this code:
def random_answerlist(self):
self.li = []
self.winning_button = random.randint(0, 3)
i = 0
while i < 20 and len(self.li) is not 4:
if i == self.winning_button:
self.li.append(self.flags[self.current_flag][0])
else:
new_value = self.random_value()
if self.flags[new_value][0] not in self.li:
self.li.append(self.flags[new_value][0])
i += 1
return self.li
The only problem with it is that the first if-case may happen several times which should be impossible. I have searched for a good explanation to this and I can't find any.
Oh, I know the code isn't the best. But I'm kind of new to python (just a month or so) and thought this might work, but it didn't!
Do you guys know why? =)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个明显的问题是使用
is not
与len(self.li)
进行值比较。测试is not
和!=
不一样。is
测试身份(这些引用是否是同一个对象?),!=
测试相等性(这些对象是否具有相同的值?)。将您的
while
更改为:这可以解决问题吗?
One glaring problem is the usage of
is not
for a value comparision againstlen(self.li)
. The testsis not
and!=
are not the same.is
tests for identity (are these references to the same object?),!=
tests for equality (do these objects have the same value?).Change your
while
to:Does that address the issue?
是的,抱歉。
当我意识到自己是失败者时,我正在外面抽烟:
问题并不像你们所说的那样。问题是 else 情况与第一个 if-情况从同一个列表中随机生成。有时,与第一个 if-case 中的值相同的值会进入列表。
你无法解决这个问题,因为我没有发布完整的代码。
好吧,无论如何,谢谢:)
Yes, sorry.
I were out smoking when I realized I were the one failing:
The problem is not the if-case as you guys stated. The problem is that the else case generates randomly from the same list as the first if-case does. And then the same value is getting into the list sometimes as the one in the first if-case.
You couldn't solve it since I didn't post the whole code.
Well thanks anyway :)