Skip to main content
 首页 » 编程设计

Python 以特定方式追加列表

2025年05月04日12zhengyun_ustc

我知道我实际上可以按如下方式合并两个列表(在 Python 2.7 中)

list1 = ['one', 'two', 'three', 'four', 'five'] 
list2 = ['A', 'B', 'C', 'D', 'E'] 
merged = list1 + list2 
print merged 
# ['one', 'two', 'three', 'four', 'five', 'A', 'B', 'C', 'D', 'E'] 

问题是,我想在每两个 list1 之后插入一个 list2。示例:

list1 = ['one', 'two', 'three', 'four', 'five'] 
list2 = ['A', 'B', 'C', 'D', 'E'] 
after 2 of list1: 
     add 1 of list2 
print merged 
# ['one', 'two', 'A', 'three', 'four', 'B', 'five', 'six', 'C', 'seven', 'eight', 'D', 'nine', 'ten'] 

非常感谢任何帮助!

请您参考如下方法:

在这种情况下,使用原始迭代器可以生成干净的代码,您可以在迭代器上调用 next 来获取下一个值,然后将其追加到结果中,这样列表的创建就是非常直观:

list1 = ['one', 'two', 'three', 'four', 'five'] 
list2 = ['A', 'B', 'C', 'D', 'E'] 
iter_list1 = iter(list1) 
iter_list2 = iter(list2) 
 
final = [] 
try: #broken when one of the iterators runs out (and StopIteration is raised) 
    while True: 
        final.append(next(iter_list1)) 
        final.append(next(iter_list1)) 
 
        final.append(next(iter_list2)) 
except StopIteration: 
    pass 
#one will already be empty, add the remaining elements of the non-empty one to the end of the list. 
final.extend(iter_list1) 
final.extend(iter_list2) 
 
print(final)