循环创建一个元组

循环创建一个元组

问题描述:

我试图实现发送群发邮件。循环创建一个元组

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

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

datatuple = (
    ('Subject', 'Message.', '[email protected]', ['[email protected]']), 
    ('Subject', 'Message.', '[email protected]', ['[email protected]']), 
) 

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

到目前为止,我有:

recipients = notification.objects.all().values_list('username','email') 
# this returns [(u'John', u'[email protected]'), (u'Jane', u'[email protected]')] 
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) 

我一直在试图沿着这一线的东西:)实际上

1:需要 SO- tuple from a string and a list of strings

+1

你面临什么困难? –

+0

你不能给元组添加任何东西,因为元组是不可变的。改用列表。 –

+0

@DmitryBeransky不正确。它不会导致相同的对象被改变,但是元组和整数和字符串一样支持增量。 – Pynchia

如果我理解正确,这是非常简单的理解。

emails = [ 
    (u'Subject', u'Message.', u'[email protected]', [address]) 
    for name, address in recipients 
] 
send_mass_mail(emails) 

请注意,我们利用Python的能力将tuple s解包为一组命名变量。对于recipients的每个元素,我们将其第零个元素指定为name,将其第一个元素指定为address。所以在第一次迭代中,nameu'John'addressu'[email protected]'

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

emails = [ 
    (u'Subject', u'Dear {}, Message.'.format(name), u'[email protected]', [address]) 
    for name, address in recipients 
] 

由于上述的名单解析,他们导致emailslist。如果你真的需要这是一个tuple,而不是list,很简单,太:

emails = tuple(
    (u'Subject', u'Message.', u'[email protected]', [address]) 
    for name, address in recipients 
) 

对于这一块,我们实际上是通过一个生成器对象为tuple构造。这具有使用发电机的性能优点,而无需创建中间list的开销。在Python中可以接受迭代参数的地方可以做到这一点。

只是清理了一点点在这里建元组的循环(这是一个有点棘手,因为你需要额外的逗号,以确保一个元组从元组附加,而不是值)

2)移动send_mass_mail通话外循环

这应该是工作代码:

recipients = notification.objects.all().values_list('username','email') 
# this returns [(u'John', u'[email protected]'), (u'Jane', u'[email protected]')] 
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, "[email protected]", [to,]),) 
send_mass_mail(tuple(datatuple)) 

编辑: jpmc26的技术肯定是更有效的,如果你打算有一个大的邮件列表,以发送给你应该使用它。最有可能的是,你应该使用哪个代码对你个人最有意义,这样当你的需求改变时,你可以很容易地理解如何更新。