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)
任何帮助将非常感激!
在这种情况下,使用原始迭代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)
| 归档时间: |
|
| 查看次数: |
192 次 |
| 最近记录: |