Python以特定方式附加列表

use*_*843 2 python list append

我知道我实际上可以合并两个列表(在 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']
Run Code Online (Sandbox Code Playgroud)

问题是,我希望在 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']
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激!

Tad*_*sen 5

在这种情况下,使用原始迭代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)
Run Code Online (Sandbox Code Playgroud)

  • @Chris_Rands 我想成为一名老师,而不是一名优秀的编码员。我发布的那种循环对于初学者来说很容易操作和使用,没有任何晦涩的问题。一旦有人对 python 和迭代器感到满意,并且正在寻找编写更高效/更短/更易于阅读的代码的方法,并且对“zip”有什么期望,那么绝对去做——这不是我的观众为。 (4认同)