How to elegantly interleave two lists of uneven length in python?

前端 未结 8 1423
自闭症患者
自闭症患者 2021-01-04 06:13

I want to merge two lists in python, with the lists being of different lengths, so that the elements of the shorter list are as equally spaced within the final list as possi

8条回答
  •  没有蜡笔的小新
    2021-01-04 06:42

    This is basically the same as Bresenham's line algorithm. You can calculate "pixel" positions and use them as the indices into the lists.

    Where your task differs is that you only want each element to show up once. You'd need to either modify the algorithm or post-process the indices, appending the elements from the lists only the first time they appear. There is a slight ambiguity, though: when both pixel/list indices change at the same time, you'll need to pick which one to include first. This corresponds to the two different options for interleaving the lists that are mentioned in the question and a comment.

提交回复
热议问题