我正在編寫代碼來起草一封電子郵件給 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
提交
取消