我想向某些學習小組發送預定義的訊息,其中包含有關課程、日期和要學習的單元的資訊,同時只更改次要內容。為此,我創建了三個串列,如下所示:
classes = ['Math', 'English', 'History']
units = ['Unit 9', 'Unit 10', 'the Exam']
dates = ['may 11th', 'may 18th', 'may 25th']
為了呼叫每個串列項,我使用了 for陳述句(下面的最小示例):
for j in range(len(classes)):
for i in range(len(units)):
text = ''' Hello, we'll have %s classes on %s.
The topic will be %s.
''' % (classes[j], dates[i], units[i])
print(text)
此代碼為每個組列印我想要的訊息。但是,我不知道如何將這些文本中的每一個關聯到不同的變數,以便稍后在我告訴我的代碼撰寫每封電子郵件時呼叫它。
uj5u.com熱心網友回復:
第一個快速樣式建議 - 而不是使用for回圈生成數字索引
for j in range(len(classes)):
...
只需選擇一個有意義的回圈變數(例如classname)并以這種方式通過回圈遍歷該回圈變數for:
for classname in classes:
...
對于您在“并行”中遍歷它們的串列,這是該函式的經典用法,該units函式將兩個串列“壓縮”在一起并創建一個虛擬元組串列,然后您可以使用回圈遍歷兩個回圈變數兩個值并行dateszip( )for
for unit, date in zip(units, dates):
...
這些更改一起將允許您擁有有意義的變數名稱(classname, unit, date)
最后,為了“插入”您的變數,一種更新的方法稱為f-strings允許您創建帶有占位符的字串。占位符可以包含任何有效的 Python 運算式,它將被計算并插入到更大的字串中
例如:
name = "Fred"
age = 12
# f-string starts with f then a quote character
# anything inside curly braces { } is evaluated as a
# Python expression and substituted as text into the larger string
text = f"{name} is {age 1} years old on his next birthday"
然后最后將每個字串添加到不同的變數中,您可以按照海報 RufusVS 的建議進行操作,并將每個字串附加到串列中。這將允許您通過一個數字來參考每個字串。
如果你真的希望每個字串都有一個全新的變數名,你可以做一些更多的元操作,并通過寫入全域符號表為每個字串創建一個新變數,這只是 Python 用來跟蹤其全域的字典變數。
這是將每條訊息附加到串列的方法:
classes = ['Math', 'English', 'History']
units = ['Unit 9', 'Unit 10', 'the Exam']
dates = ['may 11th', 'may 18th', 'may 25th']
all_messages = [] # empty list for the messages
for classname in classes:
for unit, date in zip(units, dates):
string = (f"Hello, we'll have {classname} class on {date}\n"
f"The topic will be {unit}\n")
print(string) # for debugging
all_messages.append(string) # to save each message
print(Message 5 is", all_messages[5])
這是更多元方法,您實際上為您創建的每條訊息創建表單訊息 n 的新變數(例如 ,message0等message1)
classes = ['Math', 'English', 'History']
units = ['Unit 9', 'Unit 10', 'the Exam']
dates = ['may 11th', 'may 18th', 'may 25th']
symbol_table = globals() # get the global symbol table
count = 0 # counter to track which message variable we are creating
for classname in classes:
for unit, date in zip(units, dates):
string = (f"Hello, we'll have {classname} class on {date}\n"
f"The topic will be {unit}\n")
print(string) # for debugging
# little tricky here - create a string with the name of the
# variable you want to create (eg. 'message5')
# then use that string as the key in the globals dictionary
# the value associated with that key is the new message
# this actually creates a new global variable for each message
symbol_table[f"message{count}"] = string
count = 1
print("Message 5 is", message5)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/473843.html
