【问题标题】:Looping through to create a tuple循环创建一个元组
【发布时间】:2015-12-02 23:02:22
【问题描述】:

我正在尝试实现群发邮件。

这里是群发邮件文档:Just a link to the Django Docs

为了实现这一点,我需要创建这个元组:

datatuple = (
    ('Subject', 'Message.', 'from@example.com', ['john@example.com']),
    ('Subject', 'Message.', 'from@example.com', ['jane@example.com']),
)

我在 ORM 中查询了一些收件人的详细信息。然后我会想象会涉及一些循环,每次都会向元组添加另一个收件人。消息的所有元素都相同,除了用户名和电子邮件。

到目前为止我有:

recipients = notification.objects.all().values_list('username','email')
# this returns [(u'John', u'john@example.com'), (u'Jane', u'jane@example.com')]
for recipient in recipients:    
     to = recipient[1]               #access the email
     subject = "my big tuple loop"
     dear = recipient[0]              #access the name  
     message = "This concerns tuples!"
     #### add each recipient to datatuple
     send_mass_mail(datatuple)

我一直在尝试这样的事情: SO- tuple from a string and a list of strings

【问题讨论】:

  • 你遇到了什么麻烦?
  • 您不能向元组添加任何内容,因为元组是不可变的。请改用列表。
  • @DmitryBeransky 这不是真的。它不会导致同一个对象被更改,但元组支持增量以及整数和字符串。
  • @Ryan 你是说datatuple += (subject, message, 'from@example.com', [to, ])
  • @Ryan BTW,也许send_mass_mail(datatuple) 行应该不缩进并退出循环

标签: python django


【解决方案1】:

如果我理解正确,这很简单。

emails = [
    (u'Subject', u'Message.', u'from@example.com', [address])
    for name, address in recipients
]
send_mass_mail(emails)

请注意,我们利用 Python 将tuples 解压缩为一组命名变量的能力。对于recipients 的每个元素,我们将其第零个元素分配给name,将其第一个元素分配给address。所以在第一次迭代中,nameu'John'addressu'john@example.com'

如果您需要根据名称更改 'Message.',您可以使用字符串格式或您选择的任何其他格式/模板机制来生成消息:

emails = [
    (u'Subject', u'Dear {}, Message.'.format(name), u'from@example.com', [address])
    for name, address in recipients
]

由于以上是列表推导,它们导致emails 成为list。如果您真的需要将其设为tuple 而不是list,那也很简单:

emails = tuple(
    (u'Subject', u'Message.', u'from@example.com', [address])
    for name, address in recipients
)

对于这个,我们实际上将一个生成器对象传递给tuple 构造函数。这具有使用生成器的性能优势,而无需创建中间list。您几乎可以在 Python 中接受可迭代参数的任何地方执行此操作。

【讨论】:

    【解决方案2】:

    这里只需要一点清理:

    1) 实际上在循环中构建元组(这有点棘手,因为您需要额外的逗号来确保附加元组而不是元组中的值)

    2) 将 send_mass_mail 调用移出循环

    这应该是工作代码:

    recipients = notification.objects.all().values_list('username','email')
    # this returns [(u'John', u'john@example.com'), (u'Jane', u'jane@example.com')]
    datatuple = []
    for recipient in recipients:    
        to = recipient[1]               #access the email
        subject = "my big tuple loop"
        dear = recipient[0]              #access the name  
        message = "This concerns tuples!"
        #### add each recipient to datatuple
        datatuple.append((subject, message, "from@example.com", [to,]),)
    send_mass_mail(tuple(datatuple))
    

    编辑: jpmc26 的技术肯定更有效,如果你打算发送一个大的电子邮件列表给你,应该使用它。您很可能应该使用对您个人最有意义的代码,这样当您的需求发生变化时,您可以轻松了解如何更新。

    【讨论】:

      猜你喜欢
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 2019-08-28
      • 2016-05-08
      • 1970-01-01
      • 2012-09-21
      相关资源
      最近更新 更多