【问题标题】:Create a function that takes in a list of tuples, where each tuple has two elements创建一个接收元组列表的函数,其中每个元组有两个元素
【发布时间】:2017-02-03 01:51:53
【问题描述】:

第一个元素是客户名称(字符串),第二个元素是该客户当月的总账单(浮动)。该函数的目的是处理此列表,使用以下模板为每个客户创建“计费电子邮件”:

'Dear {},\n\nYou owe ACME Corp ${:.2f}.\n\nBest,\nACME Corp'

该函数应返回这些生成的电子邮件的列表。它应命名为“generate_billing_emails”。输入应称为“customer_data”

test_data = [("Wile E Coyote", 345.67), ("Bugs Bunny", 25.49), ("Foghorn Leghorn", 68.00), ("Tweety", 5.99)]

billing_emails = generate_billing_email(test_data)

for billing_email in billing_emails:        
    print("{}".format( billing_email ))
    print("\n\n--------")

到目前为止我的代码:

def generate_billing_email(test_data):
    billing_emails = 'Dear {},\n\nYou owe ACME Corp ${:.2f}.\n\nBest,\nACME Corp'
    return billing_emails

【问题讨论】:

  • 你的老师一定在课堂上提到过for循环和字符串format方法。
  • 他做到了,但我很困惑,因为有一个浮点数和字符串
  • @RayHarlequin 在某些语言中,区分浮点数和字符串很重要。 Python不是其中一种语言。这个问题中唯一可能重要的地方是格式字符串,并且您的教师已经为您提供了一个很好的使用{:,.2f} 来很好地格式化浮点数的地方。
  • 那么这个功能对吗?我还添加:customer_data = 0 用于 [("Wile E Coyote", 345.67), ("Bugs Bunny", 25.49), ("Foghorn Leghorn", 68.00), ("Tweety", 5.99)]: customer_data = customer_data + 1
  • 对不起,如果我听起来很愚蠢,但我对 python 很陌生。第一次编码

标签: pythonanywhere


【解决方案1】:

要完成您想做的事情,您必须使用 for 循环遍历您的数据。而且,您可以通过传入参数来使用格式函数。如果您使用浮点数、字符串、整数等,则无需告诉 Python...

我会这样重写你的函数:

def generate_billing_email(test_data):
    emails = []
    for tupe in test_data:
        emails.append("'Dear {0},\n\nYou owe ACME Corp ${1}.\n\nBest,\nACME Corp'".format(tupe[0], tupe[1]))
    return emails

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    相关资源
    最近更新 更多