首页 > 解决方案 > 如何循环遍历列表并为每个不同的值启动另一个循环?

问题描述

我有一个 python 列表,这个列表是在设定的时间范围内更新的任何文档,并且这些文档是通过列表中的设定值标识的。结果列表中可能有一个或多个。我想弄清楚的是如何循环遍历值(文档)列表并触发另一个循环,该循环遍历我拥有的另一个电子邮件列表,导致原始列表中每个文档的每个地址一个电子邮件?我试图将循环“堆叠”在彼此之上(代码片段如下所示),但这会导致每个电子邮件地址的多封电子邮件都带有完整的文档列表(即,如果列表中有两个文档,则有两封电子邮件将两份文件的详细信息发送到每个地址)。

import boto3
from botocore.exceptions import ClientError
import requests
from datetime import datetime, timedelta

#first get request to pull all current endusers
GET1 = "https://abdc.com/api"

r1 = requests.get(url = GET1, auth=('username/token','APItoken'))

#convert to python dict
data = r1.json()

#create a list of all user's email addresses
emails = [user["email"] for user in data["users"]]

#create an timestamp of previous day and convert to epoch
ts1 = datetime.today() - timedelta(days =1)
ts2 = ts1.strftime("%s")

#set start time attribute as a parameter
params = {'start_time':ts2}

#second GET reqeust to pull all articles updated in the last 24 hrs
GET2 = "https://efdg.com/api"

r2 = requests.get(url = GET2, params=params, auth=('username/token','APItoken'))

#convert to python dict
data2 = r2.json()

#create list of all the target article titles and html url
updated_docs = [articles["html_url"] for articles in data2["articles"]]
doc_title = [articles["title"] for articles in data2["articles"]]

for y in updated_doc:

   #create loop to iterate throuhg all the email addresses and send 
   individual emails to users
   for x in emails:
        # This address must be verified with Amazon SES.
        SENDER = "example@example.com"

        #To list
        RECIPIENT = x

        # Specify a configuration set. If you do not want to use a configuration
        # set, comment the following variable, and the
        # ConfigurationSetName=CONFIGURATION_SET argument below.
        #CONFIGURATION_SET = "ConfigSet"

        # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
        AWS_REGION = "us-east-1"

        # The subject line for the email.
        SUBJECT = "blah blah "

        # The email body for recipients with non-HTML email clients.
        BODY_TEXT = ("Amazon SES Test (Python)\r\n"
                     "This email was sent with Amazon SES using the "
                     "AWS SDK for Python (Boto)."
                     )

        # The HTML body of the email.
        BODY_HTML = """<html>
        <head></head>
        <body>
          <h1>l Documentation Notification</h1>
          <p1>Please click the link below for the most current version of this document.<br>
          <br>
          """+str(doc_title)+"""<br>
          <br>
          """+str(updated_docs)+"""
          </p1>
        </body>
        </html>
                    """

        # The character encoding for the email.
        CHARSET = "UTF-8"

        # Create a new SES resource and specify a region.
        client = boto3.client('ses', region_name=AWS_REGION)

        # Try to send the email.
        try:
            # Provide the contents of the email.
            response = client.send_email(
                Destination={
                    'ToAddresses': [
                        RECIPIENT,
                    ],
                },
                Message={
                    'Body': {
                        'Html': {
                            'Charset': CHARSET,
                            'Data': BODY_HTML,
                        },
                        'Text': {
                            'Charset': CHARSET,
                            'Data': BODY_TEXT,
                        },
                    },
                    'Subject': {
                        'Charset': CHARSET,
                        'Data': SUBJECT,
                    },
                },
                Source=SENDER,
                # If you are not using a configuration set, comment or delete the
                # following line
                #ConfigurationSetName=CONFIGURATION_SET,
            )
        # Display an error if something goes wrong.
        except ClientError as e:
            print(e.response['Error']['Message'])
        else:
            print("Email sent! Message ID:"),
            print(response['MessageId'])

标签: python

解决方案


所以,你已经完全改变了你的代码,所以我很困惑,但如果我能正确地在两行之间阅读,你的意思是这样的:

#create loop to iterate through all documents in the list
for article in data2["articles"]:

    #create loop to iterate through all the email addresses and send individual emails to 
    users
    for x in emails:
        # This address must be verified with Amazon SES.
        SENDER = "example@example.com"

        #To list
        RECIPIENT = x

        # The HTML body of the email.
        BODY_HTML = """<html>
        <head></head>
        <body>
          <h1>l Documentation Notification</h1>
          <p1>Please click the link below for the most current version of this document.<br>
          <br>
          """+str(article["title"])+"""<br>
          <br>
          """+str(article["html_url"])+"""
          </p1>
        </body>
        </html>
                    """

请注意我如何迭代data2["articles"]和更新BODY_HTMLwith article["title"]and article["html_url"]


推荐阅读