omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    Help with script

    Editorial
    2
    2
    1741
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Jozh
      Jozh last edited by

      Is this the best way to say output a list of say the 10 closest birthday? I think not. Thank

      import contacts
      from datetime import datetime
      import operator
      import workflow
      import dialogs
      
      days_list = []
      people = contacts.get_all_people()
      now = datetime.now()
      for p in people:
        b = p.birthday
        if b:
          next_birthday = datetime(now.year, b.month, b.day)
          if next_birthday < now:
            next_birthday = datetime(now.year + 1, b.month, b.day)
          days = (next_birthday - now).days
          days_list.append({'name': p.full_name, 'days': days})
      
      if not days_list:
        print 'You don\'t have any birthdays in your address book.'
      else:
        days_list.sort(key=operator.itemgetter('days'))
        for item in days_list[:1]:
          text = '* %s in %i days' % (item['name'], item['days'])
        for item in days_list[:2]:
          text2 = '* %s in %i days' % (item['name'], item['days'])
        for item in days_list[:3]:
          text3 = '* %s in %i days' % (item['name'], item['days'])
        for item in days_list[:4]:
          text4 = '* %s in %i days' % (item['name'], item['days'])
        for item in days_list[:5]:
          text5 = '* %s in %i days' % (item['name'], item['days'])  
      birthday_list = '\n'.join([text, text2, text3,text4,text5]) 
      workflow.set_output(birthday_list)```
      1 Reply Last reply Reply Quote 0
      • ccc
        ccc last edited by ccc

        It looks good to me. The following could save you 9 lines of code:

          fmt = '* {name} in {days} days'
          birthday_list = '\n'.join(fmt.format(**item) for item in days_list[:5])
        
        1 Reply Last reply Reply Quote 1
        • First post
          Last post
        Powered by NodeBB Forums | Contributors