【发布时间】:2021-01-11 06:31:38
【问题描述】:
我有一个较大的列表,我想通过较小列表的元素分配或以其他方式对其执行操作,但只执行一次。例如:
emailList = ['tom@gmail.com', 'dick@gmail.com', 'harry@gmail.com', 'jane@gmail.com']
fileList = ['file_1.zip', 'file_2.zip']
我想将 fileList 的元素交替分配给 emailList 的元素。所以:
tom@gmail.com -> file_1.zip
dick@gmail.com -> file_2.zip
harry@gmail.com -> file_1.zip
jane@gmail.com -> file_2.zip
我有这个...一半工作(为简单起见,我只是使用打印语句来表示操作):
for email in emailList:
for file in zippedList:
print(email + "will receive " + file)
zippedList.pop(0)
产量:
Email: tom@gmail.com
will receive Contest_Packet_1.zip
Email: dick@gmail.com
will receive Contest_Packet_2.zip
当然问题是,一旦 zippedList 为空,它就会结束,并且不再进行任何分配。但是,当我不弹出较小列表的元素时,较大列表的元素每个都将分配较小列表中的两个元素或以其他方式执行。它产生了这个:
Email: tom@gmail.com
will receive Contest_Packet_1.zip
Email: tom@gmail.com
will receive Contest_Packet_2.zip
Email: dick@regula.one
will receive Contest_Packet_1.zip
Email: dick@regula.one
will receive Contest_Packet_2.zip
Email: harry@gmail.com
will receive Contest_Packet_1.zip
Email: harry@gmail.com
will receive Contest_Packet_2.zip
Email: jane@gmail.com
will receive Contest_Packet_1.zip
Email: jane@gmail.com
will receive Contest_Packet_2.zip
当然有更简单的方法可以做到这一点。想法?
【问题讨论】:
-
嗨,也许
itertools.cycle可能会感兴趣stackoverflow.com/questions/19686533/… -
我会检查一下,非常感谢@IronMan
标签: python