I have a list of the following form:
[[0, 5.1, 3.5, 1.4, 0.2],
[0, 4.9, 3.0, 1.4, 0.2],
[0, 4.7, 3.2, 1.3, 0.2],
[1, 4.6, 3.1, 1.5, 0.2],
[1, 5.0, 3.6, 1.4, 0.2],
[1, 5.4, 3.9, 1.7, 0.4],
[1, 4.6, 3.4, 1.4, 0.3]]
I want to slice out the first column and add it as a new element to each row of data (so at each odd position in the list), changing it to the following form:
[[5.1, 3.5, 1.4, 0.2], [0],
[4.9, 3.0, 1.4, 0.2], [0],
[4.7, 3.2, 1.3, 0.2], [0],
[4.6, 3.1, 1.5, 0.2], [1],
[5.0, 3.6, 1.4, 0.2], [1],
[5.4, 3.9, 1.7, 0.4], [1],
[4.6, 3.4, 1.4, 0.3], [1],]
How could I do this?
So far, I have extracted the necessary information in the following ways:
targets = [element[0] for element in dataset]
features = dataset[1:]
Python supports slice assignment operation, which allows us to make a bunch of neat operations over an existing list. Unlike previous slice operations, these mutate the original object in place. That's why they are not applicable to immutable sequential types.
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ] .
Try indexing and then get flattened list- i used list comprehension for flattening.
>>>l=[[0, 5.1, 3.5, 1.4, 0.2],
[0, 4.9, 3.0, 1.4, 0.2],
[0, 4.7, 3.2, 1.3, 0.2],
[1, 4.6, 3.1, 1.5, 0.2],
[1, 5.0, 3.6, 1.4, 0.2],
[1, 5.4, 3.9, 1.7, 0.4],
[1, 4.6, 3.4, 1.4, 0.3]]
>>>[[i[1:],[i[0]]] for i in l]#get sliced list of lists
>>>[[[5.1, 3.5, 1.4, 0.2], [0]], [[4.9, 3.0, 1.4, 0.2], [0]], [[4.7, 3.2, 1.3, 0.2], [0]], [[4.6, 3.1, 1.5, 0.2], [1]], [[5.0, 3.6, 1.4, 0.2], [1]], [[5.4, 3.9, 1.7, 0.4], [1]], [[4.6, 3.4, 1.4, 0.3], [1]]]
>>>d=[[i[1:],[i[0]]] for i in l]
>>>[item for sublist in d for item in sublist]#flatten list d
>>>[[5.1, 3.5, 1.4, 0.2], [0], [4.9, 3.0, 1.4, 0.2], [0], [4.7, 3.2, 1.3, 0.2], [0], [4.6, 3.1, 1.5, 0.2], [1], [5.0, 3.6, 1.4, 0.2], [1], [5.4, 3.9, 1.7, 0.4], [1], [4.6, 3.4, 1.4, 0.3], [1]]
Just oneliner alternative-
[item for sublist in [[i[1:],[i[0]]] for i in l] for item in sublist] #Here l is that list
List comprehensions are nice but can be a bit hard to scan. Loops are still useful, especially when combined with extend
:
res = []
for entry in dataset:
res.extend([entry[1:], entry[:1]])
now:
import pprint
pprint.pprint(res)
prints:
[[5.1, 3.5, 1.4, 0.2],
[0],
[4.9, 3.0, 1.4, 0.2],
[0],
[4.7, 3.2, 1.3, 0.2],
[0],
[4.6, 3.1, 1.5, 0.2],
[1],
[5.0, 3.6, 1.4, 0.2],
[1],
[5.4, 3.9, 1.7, 0.4],
[1],
[4.6, 3.4, 1.4, 0.3],
[1]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With