Itertools拉链两个列表相互之间(Itertools Zip Two List into each other)
c = list(itertools.chain.from_iterable(zip(list_a, list_b)))
我有两个list list_a和list_b
list_a有一个元素而不是list_b ,我想插入b的一个元素的两个元素之间。
不幸的是,上面的方法删除了结果列表c中list_a的最后一个元素。 我怎样才能解决这个问题? Python 2.7
c = list(itertools.chain.from_iterable(zip(list_a, list_b)))I have two list list_a and list_b
list_a has one more element than list_b and i want to insert between two elements of a one element of b.
Unfortunately this method from above deletes the last element of list_a in the result list c. How can i fix this? Python 2.7
最满意答案
我不太了解itertools更多,但如果你只需list_a的最后一个元素list_a到c ,为什么不这样做呢?
import itertools list_a = [1,3,5,7,9] list_b = [2,4,6,8] c = list(itertools.chain.from_iterable(zip(list_a, list_b))) # c is [1, 2, 3, 4, 5, 6, 7, 8] c.append(list_a[-1]) # after append c is [1, 2, 3, 4, 5, 6, 7, 8, 9]I don't know enough about itertools to say much more, but if you only need to append the last element of list_a to c, why not do just that?
import itertools list_a = [1,3,5,7,9] list_b = [2,4,6,8] c = list(itertools.chain.from_iterable(zip(list_a, list_b))) # c is [1, 2, 3, 4, 5, 6, 7, 8] c.append(list_a[-1]) # after append c is [1, 2, 3, 4, 5, 6, 7, 8, 9]更多推荐
发布评论