Reputation: 111
How would you short these two list comprehension to one line? I would like to code as one line. My way seems too long. I feel like there is another way to code it.
y = [array[i][0] for i in range(len(array))]
x = [i for i in range(len(array))]
x, y = [i for i in range(len(array))], [array[i][0] for i in range(len(array))]
Upvotes: 0
Views: 2270
Reputation: 402423
Assuming you want to extract the first column of a 2D list along with it's indices, you'd use enumerate
with inverse-zip
unpacking:
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x, y = zip(*enumerate([r[0] for r in array]))
print(x)
(0, 1, 2)
print(y)
(1, 4, 7)
x
is the index, and y
is the row vector. As seen above, this method results in your data being extracted out as tuple
s (not list
s), and will fail when array
is empty.
So, as @user2357112 said in their comment, please don't endeavour to shove all your code into one line – do it only when it can be done and makes sense to do so.
Furthermore, to extend the discussion in comments, the best way to do this would be to follow a 2-step approach as shown by @Rakesh in their answer:
x = list(range(len(array)))
y = [r[0] for r in array]
print(x)
[0, 1, 2]
print(y)
[1, 4, 7]
This doesn't suffer from the drawbacks mentioned above.
Upvotes: 6
Reputation: 77414
x, y = list(map(list, zip(*[(i, r[0]) for i, r in enumerate(a)]))) or ([], [])
disclaimer: I think it's a situation where one-liner-ness is a bad thing.
Upvotes: 0
Reputation: 82765
This should help
x = range(len(array)) #range returns list
y = [i[0] for i in array] #you can access the element in the list without range or len
Upvotes: 2