如何在 python 中更好地重写 if-else 语句
How to rewrite if-else statements better in python
我有一些像下面这样的 if-else 语句,基本上它像 charm 一样工作,但是条件经常改变,它可以添加更多,....所以我认为 if-else 方式不是优化的。这就是为什么我想知道是否有更好的解决方案来减少为此重复的代码。
name1, name2, name3, name4, name5 = "David", "Luke", "Kate", "Bobby", "Megan"
sentences = ["Megan is my friend", "Boddy is my friend"]
existed_name = []
for sentence in sentences:
if name1 in sentence:
existed_name.append(name1)
elif name2 in sentence:
existed_name.append(name2)
elif name3 in sentence:
existed_name.append(name3)
elif name4 in sentence:
existed_name.append(name4)
elif name5 in sentence:
existed_name.append(name5)
else:
existed_name.append('Empty')
非常感谢你帮助我。
如果您将所有名称定义在一个列表中而不是作为单独的变量,则可以为此使用简单的嵌套循环。
names = ["David", "Luke", "Kate", "Bobby", "Megan"]
sentences = ["Megan is my friend", "Boddy is my friend"]
existing_names = []
for sentence in sentences:
for name in names:
if name in sentence:
existing_names.append(name)
print(existing_names)
# ["Megan"]
添加到 Abhinav 的回答中,您可以有一个标志来查看该名称是否存在。
names = ["David", "Luke", "Kate", "Bobby", "Megan"]
sentences = ["Megan is my friend", "Boddy is my friend"]
for sentence in sentences:
existed = False
for name in names:
if name in sentence:
existed_name.append(name)
existed = True
break
if not existed:
existed_name.append("Empty")
如果你更喜欢一个线性列表理解
names = ["David", "Luke", "Kate", "Bobby", "Megan"]
sentences = ["Megan is my friend", "Boddy is my friend"]
existed_name = [name for name in names for sentence in sentences if name in sentence]
我有一些像下面这样的 if-else 语句,基本上它像 charm 一样工作,但是条件经常改变,它可以添加更多,....所以我认为 if-else 方式不是优化的。这就是为什么我想知道是否有更好的解决方案来减少为此重复的代码。
name1, name2, name3, name4, name5 = "David", "Luke", "Kate", "Bobby", "Megan"
sentences = ["Megan is my friend", "Boddy is my friend"]
existed_name = []
for sentence in sentences:
if name1 in sentence:
existed_name.append(name1)
elif name2 in sentence:
existed_name.append(name2)
elif name3 in sentence:
existed_name.append(name3)
elif name4 in sentence:
existed_name.append(name4)
elif name5 in sentence:
existed_name.append(name5)
else:
existed_name.append('Empty')
非常感谢你帮助我。
如果您将所有名称定义在一个列表中而不是作为单独的变量,则可以为此使用简单的嵌套循环。
names = ["David", "Luke", "Kate", "Bobby", "Megan"]
sentences = ["Megan is my friend", "Boddy is my friend"]
existing_names = []
for sentence in sentences:
for name in names:
if name in sentence:
existing_names.append(name)
print(existing_names)
# ["Megan"]
添加到 Abhinav 的回答中,您可以有一个标志来查看该名称是否存在。
names = ["David", "Luke", "Kate", "Bobby", "Megan"]
sentences = ["Megan is my friend", "Boddy is my friend"]
for sentence in sentences:
existed = False
for name in names:
if name in sentence:
existed_name.append(name)
existed = True
break
if not existed:
existed_name.append("Empty")
如果你更喜欢一个线性列表理解
names = ["David", "Luke", "Kate", "Bobby", "Megan"]
sentences = ["Megan is my friend", "Boddy is my friend"]
existed_name = [name for name in names for sentence in sentences if name in sentence]