我正在编写代码来起草一封电子邮件给 1 到 4 个收件人之间的任何地方。收件人是从 Excel 工作簿中提取的。因此,如果只有 3 个收件人,Person4 的单元格将为空白。问题是,每次有不同数量的收件人时,为一封单独的电子邮件编写代码似乎不是很 Pythonic。我想为一封电子邮件编写一个代码块,如果它是 None 则忽略一个被调用的变量# collect recipent names from workbookPerson1 = sheet['BG1'].valuePerson2 = sheet['BH1'].valuePerson3 = sheet['BI1'].valuePerson4 = sheet['BJ1'].value# draft emailif 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*')有没有更聪明的方法来写这个?任意数量的收件人只有一个代码块?
1 回答
30秒到达战场
TA贡献1828条经验 获得超6个赞
将您的名字视为一个数组:
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 工作表范围执行此操作,而无需首先将人员姓名分配给各个变量。
添加回答
举报
0/150
提交
取消