Reputation: 51
I have the ohlc
list as below:
ohlc = [["open", "high", "low", "close"],
[100, 110, 70, 100],
[200, 210, 180, 190],
[300, 310, 300, 310]]
I want to slice it as:
[["open"],[100],[200],[300]]
We can easily slice that list using numpy
, but I don't know how to do it without numpy
's help.
I tried the method listed below but it didn't show the value I wanted:
ohlc[:][0]
ohlc[:][:1]
ohlc[0][:]
Upvotes: 0
Views: 91
Reputation: 114035
The zip
function gets you tuples containing elements from the i
-th index of every sublist:
In [217]: ohlc = [["open", "high", "low", "close"],
...: [100, 110, 70, 100],
...: [200, 210, 180, 190],
...: [300, 310, 300, 310]]
...:
In [218]: for t in zip(*ohlc): print(t)
('open', 100, 200, 300)
('high', 110, 210, 310)
('low', 70, 180, 300)
('close', 100, 190, 310)
You're looking for the first one of these, you call on your friend next()
.
In [219]: next(zip(*ohlc))
Out[219]: ('open', 100, 200, 300)
But that's just a single tuple with all the elements and not a list of lists like you wanted, so use a list comprehension:
In [220]: [[t] for t in next(zip(*ohlc))]
Out[220]: [['open'], [100], [200], [300]]
Upvotes: 3
Reputation: 36
def slice_list(input):
ans = []
for x in input:
ans.append(x[0])
return ans
Upvotes: 1
Reputation: 470
Can it be the right solution this?
list_ = []
for i in ohlc:
list_.append((i[0]))
Upvotes: 1
Reputation: 50909
You can iterate over the list and take the element in index in every sub list
ohlc = [["open", "high", "low", "close"],
[100, 110, 70, 100],
[200, 210, 180, 190],
[300, 310, 300, 310]]
index = 0
result = [[o[index]] for o in ohlc] # [['open'], [100], [200], [300]]
Upvotes: 2