我正在编写代码,起草电子邮件之间的任何1到4个收件人。 收件人是从Excel工作簿中提取的。 因此,如果只有3个收件人,则Person4的单元格将为空。 麻烦的是,为不同数量的收件人编写单独的电子邮件代码似乎不太符合Python。 我想为一封电子邮件编写一段代码,如果调用的变量为None,则忽略它
# collect recipent names from workbook
Person1 = sheet['BG1'].value
Person2 = sheet['BH1'].value
Person3 = sheet['BI1'].value
Person4 = sheet['BJ1'].value
# draft email
if Person4 != None:
print('Dear ' + Person1 + ', ' + Person2 + ', ' + Person3 + ', and ' + Person4 + ',\n' +
'The faculty members of ... *continued body of email*')
elif Person3 != None:
print('Dear ' + Person1 + ', ' + Person2 + ', and ' + Person3 + ',\n' +
'The faculty members of ... *continued body of email*')
elif Person2 != None:
print('Dear ' + Person1 + ', and ' + Person2 + ',\n' +
'The faculty members of ... *continued body of email*')
else:
print('Dear ' + Person1 + ',\n' +
'The faculty members of ... *continued body of email*')
有没有更聪明的方式来写这个? 任何数量的收件人只能使用一个代码块?
将姓名视为数组:
names = ', '.join(people[:-1]) + ' and ' + people[-1] if len(people) > 1 else people[0]
print(f'Dear {names},\n')
要填充people
数组,您可以执行以下操作
people = [person for person in (Person1, Person2, Person3, Person4) if person]
可能还有一种方法可以直接使用Excel工作表范围来完成这一操作,而不必首先将人员的姓名分配给各个变量。