python - Using a constantly changing variable to define a list -
i want make piece of code pulls title , link off rss feed , compiles variable can used in message body. problem body gets redefined every time pull info off rss. new programming , python, , under impression using list best thing do.
for in range(3): messagetitle = feed['items'][i].title messagelink = " - ",feed['items'][i]['link'] body = "%s%s%s%s" % (messagetitle,"\n","\n", messagelink) #in unicode gmail_user = "user@gmail.com" gmail_pwd = "pw" mail("user@gmail.com", "reddit update", body)
i going insert list below body, , use body define it.. like:
list[i] = [body]
am on right track?
there variety of design patterns can consider using. demonstrate few don't need use [i]
even:
accumulator:
messages = [] feeditem in feed['items']: message = {'title':..., ...} message['link'] = ... # alternative messages += [message] # or messages.append(data) print(messages)
mapping (often elegant solution in simple cases this):
def makemessage(feeditem): message = {'title':..., ...} return message messages = [makemessage(fi) fi in feed['items']] print(messages)
generators:
def makemessages(feeditems): item in feeditems: message = {'title':..., ...} yield message messages = list( makemessages(feed['items']) )
unrelated addendum: might consider making class messages:
class message(object): def __init__(self, title, link, body): self.title = title self.link = link self.body = body def __str__(self): return ... def __repr__(self): return self.__str__()
Comments
Post a Comment