Python 运行一个不应该运行的 if-case!

发布于 2024-09-20 00:17:01 字数 648 浏览 5 评论 0原文

我有这样的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

感悟人生的甜 2024-09-27 00:17:01

一个明显的问题是使用 is notlen(self.li) 进行值比较。测试 is not!= 不一样。 is 测试身份(这些引用是否是同一个对象?),!= 测试相等性(这些对象是否具有相同的值?)。

将您的 while 更改为:

while i < 20 and len(self.li) != 4:

这可以解决问题吗?

One glaring problem is the usage of is not for a value comparision against len(self.li). The tests is 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:

while i < 20 and len(self.li) != 4:

Does that address the issue?

巾帼英雄 2024-09-27 00:17:01

是的,抱歉。

当我意识到自己是失败者时,我正在外面抽烟:

问题并不像你们所说的那样。问题是 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 :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文