This is a tutorial video from my new book “Python One-Liners” with NoStarch press (San Francisco 2020).
Grab your Python One-Liner Superpower now! (Amazon Link)
Here’s the code that shows you how to sample a two-dimensional Python list—including only every other list element in the resulting two-dimensional Python list. All of this happens in a single line of code:
## Data (daily stock prices ($)) price = [[9.9, 9.8, 9.8, 9.4, 9.5, 9.7], [9.5, 9.4, 9.4, 9.3, 9.2, 9.1], [8.4, 7.9, 7.9, 8.1, 8.0, 8.0], [7.1, 5.9, 4.8, 4.8, 4.7, 3.9]] sample = [line[::2] for line in price] print(sample) # [[9.9, 9.8, 9.5], [9.5, 9.4, 9.2], [8.4, 7.9, 8.0], [7.1, 4.8, 4.7]]
Try it yourself:
The code simply removes every other element from each row in the 2D matrix.
Check out the following Finxter tutorials to learn about the necessary background:
Related articles: