我想在Python中编写一个函数,它根据输入索引的值返回不同的固定值.
在其他语言中,我会使用switch或case声明,但Python似乎没有switch声明.在这种情况下,推荐的Python解决方案是什么?
C/C++、C#、Java、JavaScript 和 Pascal (参考)等编程语言具有switchandcase语句(有时也称为selector inspect)的组合,允许您根据多个条件检查一个值以执行某些操作。
my_value = 10;
switch(my_value) {
case 10:
print("The number is ten");
case 2*10:
print("The number is the double of ten");
case 100:
print("The number is one hundred");
default:
print("The number is none of 10, 2*10 or 100");
}
Run Code Online (Sandbox Code Playgroud)
描述switch-case结构的特殊语法的伪代码。
意识到像dictionary-lookups这样的功能等价物,是否有与上述编程结构完全相同的语法?
python syntax pattern-matching switch-statement conditional-statements
我创建了以下函数,它获取成员的登录日期和合同长度,并返回修改后的数据帧,其中包含每个成员的到期日期。该函数按预期工作,但我想知道是否有更清晰的方式来编写嵌套函数month_to_num(ind)。我知道 python 没有实现cases,但是有没有办法重写所有语句if/elif/else?
def renewal_date(df):
def month_to_num(ind):
if (df.loc[ind, "Contract Type"] == "1 Month"):
return 1
elif (df.loc[ind, "Contract Type"] == "3 Months Prom" or
df.loc[ind, "Contract Type"] == "3 Month"):
return 3
elif (df.loc[ind, "Contract Type"] == "4 Month Promo"):
return 4
elif (df.loc[ind, "Contract Type"] == "6 Months"):
return 6
else:
return 12
for z in range(0, len(df)):
exp_date = (df.loc[z, "Date-Joined"] +
relativedelta(months=+month_to_num(z)))
df.set_value(z,"Date-Renewal", exp_date)
return df
Run Code Online (Sandbox Code Playgroud) 我正在编写一个Python程序,我需要在if-else情况下选择1到9之间的数字,每个数字都分配给一个类.有关如何缩短此代码的任何建议?
import randint
variable1 = randint(1, 9)
if variable1 >= 9:
print ("Your class is Tiefling")
else:
if variable1 >= 8:
print ("Your class is Half-Orc")
else:
if variable1 >= 7:
print ("Your class is Half-Elf")
else:
if variable1 >= 6:
print ("Your class is Gnome")
else:
if variable1 >= 5:
print ("Your class is Dragonborn")
else:
if variable1 >= 4:
print ("Your class is Human")
else:
if variable1 >= 3:
print ("Your class is Halfling")
else:
if variable1 >= …Run Code Online (Sandbox Code Playgroud) 所以说我必须阅读用户说的话,我的程序按照他们说的做。像这样的东西:
userinstructions = input('What action would you like me to do?')
if userinstructions == 'walk':
walk()
elif userinstructions == 'sleep':
sleep()
elif userinstructions == 'eat':
eat()
elif userinstructions == 'talk':
talk()
Run Code Online (Sandbox Code Playgroud)
现在,假设有数百种可能性,就像在现实生活中一样。我不想为可能数百个语句做 if 语句。有没有办法让它更快并且代码更少?就像一个循环或其他东西。我已经玩了一段时间,但我想不出任何东西。