Remove specific elements from list with a pattern - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Remove specific elements from list with a pattern (/thread-30182.html) |
Remove specific elements from list with a pattern - Xalagy - Oct-10-2020 #Hi everyone, here is my problem: # My Printer-Software got an error while selecting the double printing feature # My initial goal was to print 4 pages on each side of the printing paper #(4 in the front and 4 in the back) #I need a list that follows this Pattern: #[1, 2, 3, 4, 9, 10, 11, 12, 17, 18, 19, 20, 25, 26, 27, 28] (for the front pages) #[5, 6, 7, 8, 13, 14, 15, 16, 21, 22, 23, 24, 29, 30, 31, 32] (for the back pages) # I need to expand this list to 8000 but with a decent code... input = 8000 output = list(range(input + 1)) del output[0] print(output) #Here I am stuck because this list follows this order [1, 2, 3, 4,...]. How can I change it to the desired list structure like above? RE: Remove specific elements from list with a pattern - scidam - Oct-10-2020 Try the following: >>> N = 9 >>> sum([list(range(i, j)) for i, j in zip([4*k+1 for k in range(N)][1::2], [4*k + 5 for k in range(N)][1::2])], []) [5, 6, 7, 8, 13, 14, 15, 16, 21, 22, 23, 24, 29, 30, 31, 32] >>> sum([list(range(i, j)) for i, j in zip([4*k+1 for k in range(N)][0::2], [4*k + 5 for k in range(N)][0::2])], []) [1, 2, 3, 4, 9, 10, 11, 12, 17, 18, 19, 20, 25, 26, 27, 28, 33, 34, 35, 36] RE: Remove specific elements from list with a pattern - bowlofred - Oct-11-2020 Maybe not the most standard way, but I would use compress and cycle here to create two iterators for the front and the back. from itertools import cycle, compress n = 32 front = compress(range(1,n+1), cycle([1]*4 + [0]*4)) rear = compress(range(1,n+1), cycle([0]*4 + [1]*4)) print(f"front: {list(front)}") print(f"rear: {list(rear)}")
RE: Remove specific elements from list with a pattern - Xalagy - Oct-11-2020 (Oct-11-2020, 01:30 AM)bowlofred Wrote: Maybe not the most standard way, but I would use compress and cycle here to create two iterators for the front and the back. an elegant way. thank you!!! |