0

I'm looking for a simple way to modify a 2D list as shown below. Starting with a list such as this:

1,2,3
4,5,6
7,8,9

I want to create a list that looks like this:

1,2
4,5
7,8
1,3
4,6
7,9

Which is just the first and second column with the first and third column appended to the bottom. I'm sure there's a simple way of doing this, but I'm just not familiar enough with the way Python lists are structured and it's driving me crazy.

Thanks.

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by Gribouillis
1

Use list comprehensions

>>> L = [ list(range(1+k, 4+k)) for k in range(0,9,3)]
>>> L
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> LL = [x[:2] for x in L] + [[x[0], x[2]] for x in L]
>>> LL
[[1, 2], [4, 5], [7, 8], [1, 3], [4, 6], [7, 9]]
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.