我有一個較大的列表,我想對其進行分配或以其他方式對較小列表的元素執行操作,但只執行一次。例如:emailList = ['[email protected]', '[email protected]', '[email protected]', '[email protected]']fileList = ['file_1.zip', 'file_2.zip']我想交替地將 fileList 的元素分配給 emailList 的元素。所以:[email protected] -> [email protected] -> [email protected] -> [email protected] -> file_2.zip我有這個......一半工作(為了簡單起見,我只是使用 print 語句來表示動作): for email in emailList: for file in zippedList: print(email + "will receive " + file) zippedList.pop(0)產量: Email: [email protected] will receive Contest_Packet_1.zip Email: [email protected] will receive Contest_Packet_2.zip當然,問題是一旦 zippedList 為空,它就結束,并且不再進行進一步的分配。但是,當我不彈出較小列表的元素時,較大列表的元素都會獲得分配或以其他方式操作的較小列表中的兩個元素。它產生這樣的結果: Email: [email protected] will receive Contest_Packet_1.zip Email: [email protected] will receive Contest_Packet_2.zip Email: [email protected] will receive Contest_Packet_1.zip Email: [email protected] will receive Contest_Packet_2.zip Email: [email protected] will receive Contest_Packet_1.zip Email: [email protected] will receive Contest_Packet_2.zip Email: [email protected] will receive Contest_Packet_1.zip Email: [email protected] will receive Contest_Packet_2.zip當然有一種更簡單的方法可以做到這一點。想法?
1 回答

神不在的星期二
TA貢獻1963條經驗 獲得超6個贊
可能最簡單的方法是根據當前迭代的索引是否為偶數來分配值。您可以為此使用enumerate() 。下面的代碼將當前列表索引分配給索引變量,并將當前電子郵件分配給電子郵件變量。現在只需單步執行并將值一個接一個地分配給列表即可:
emailList = ['[email protected]', '[email protected]', '[email protected]', '[email protected]']
fileList = ['file_1.zip', 'file_2.zip']
for index, email in enumerate(emailList):
? ? ? if index %2 ==0 : # Even numbers
? ? ? ? ? ? print(f"Email: {email}, File: {fileList[0]}")
? ? ? else: # odd numbers
? ? ? ? ? ? print(f"Email: {email}, File: {fileList[1]}")
添加回答
舉報
0/150
提交
取消