【问题标题】:How can I achieve case condition in python? [closed]如何在 python 中实现 case 条件? [关闭]
【发布时间】:2016-01-22 17:33:54
【问题描述】:

我正在尝试使用 case 语句来实现这一点

k=[]
for i in range(1,100):
     if i%3 and i%5 == 0:
            i=i,"divides with both"
     elif i%3 ==0:
            i =i,"divides with 3 "
     elif i%5 == 0:
            i = i,"divides with 5"
     else:
            i=i
     k.append(i)

【问题讨论】:

  • 你为什么要打扰i=i
  • 该代码有什么特殊问题吗?
  • 我正在尝试在不使用 if 条件的情况下实现类似的功能
  • 这是 FizzBu​​zz 问题(谷歌搜索),这是作为计算机课程的家庭作业分配给您的吗?

标签: python case conditional-statements


【解决方案1】:

我最初的反应(如上面的评论)是这看起来像是一个家庭作业问题,不应该出现在 StackOverflow 上。

我的第二个回应是,您不应该尝试在 Python 中模拟这种风格的 switch 语句,因为它将数据嵌入到编程不佳的代码中。

我的第三个回答是,在代码中完全没有任何“if”的情况下实现此功能实际上是一个棘手的问题。所以这是我古怪的解决方案:

CASES = ("divides with both", False, False, "divides with 3", False, "divides with 5", "divides with 3", False, False, "divides with 3", "divides with 5", False, "divides with 3", False, False)

LIMIT = 100

k = []

for n in range (1, LIMIT + 1):
    result = ((n, CASES[n % len(CASES)]), n)

    k.append(result[result[0][1] == False])

print(k)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-18
    • 2017-06-13
    • 2022-06-14
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    相关资源
    最近更新 更多