Home > Software design >  How to rewrite if-else statements better in python
How to rewrite if-else statements better in python

Time:02-22

I have some if-else statement like below, basically it works like charm, but the conditions're changed frequently, it can add more,.... So I think if-else way isn't optimize. That's why I wonder if there are a better solution to reduce code duplicated for that.

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')

Thank you so much for helping me out.

CodePudding user response:

Adding to Abhinav's answer, you can have a flag to see if the name existed or not.

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")        

CodePudding user response:

You could use a simple nested loop for this if you define all the names in a single list instead of as separate variables.

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"]

CodePudding user response:

If you prefer one liner list comprehension

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]
  • Related