函数python中的条件返回

时间:2017-02-18 02:19:06

标签: python function

我想建立一个基于hashtag返回其派对的函数。这是我得到的:

def party(tw) #define party by compare hashtag to a predefined list
    #extract hashtag words from tw, and store them in tag_dict
    tag_dict={tag.strip("#") for tag in tw.split() if tag.startswith("#")} 
    tag in tag_dict

    #Compare each hashtag with Party Number of each hash tag, assign and party number to each hashtag
    party_number={k:int(party_tag[k]) for k in tag_dict if k in party_tag}

    #extract the value of party number to a variable: number
    number = party_number.values()

    if number==1
        return "Liberal"
    if number==2
        return "Conservative"
    if number==3
        return "NPD"
    if number==0
        return "Other"

如何编写条件退货?如果推文有多个派对标签,我该如何处理呢?

1 个答案:

答案 0 :(得分:0)

如果它总是一个整数,你可以构建一个列表并根据该列表返回适当的值。如:

from random import randint

def return_something():
  parties = ["Other", "Liberal", "Conservative", "NPD"]
  number = randint(0,3)
  print(number)
  try: #return number if exist (could change "not found" to "Other"
    return parties[number]
  except IndexError: #I.E. not in the list
    return "Party not found."

print(return_something())

如果它有字符串值,您可以使用字典,例如此示例代码:

parties = {'dem': "Liberal", 'rep': "Conservative", 'market': "NPD"}
#Defining the dictionary out of the function so it doesn't have to be rebuilt

def return_something(p):
  return parties.get(p, 'Other') #fetches and returns a value or a default ("Other")

party = "not in tag" #or whatever you use to get values
print(return_something(party))

或者:

def return_something(p):
    return {
        'dem': "Liberal", 
        'rep': "Conservative", 
        'market': "NPD"
    }.get(p, "Other")

print(return_something("market"))