简体   繁体   English

没有 numpy 的列表切片

[英]List slicing without numpy

I have the ohlc list as below:我的ohlc列表如下:

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.我们可以使用numpy轻松分割该列表,但如果没有numpy的帮助,我不知道该怎么做。

I tried the method listed below but it didn't show the value I wanted:我尝试了下面列出的方法,但没有显示我想要的值:

ohlc[:][0]
ohlc[:][:1]
ohlc[0][:]

The zip function gets you tuples containing elements from the i -th index of every sublist:zip function 为您提供包含每个子列表的第i个索引中的元素的元组:

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() .你正在寻找其中的第一个,你打电话给你的朋友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]]

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]]

Can it be the right solution this?这可以是正确的解决方案吗?

list_ = []
for i in ohlc:
   list_.append((i[0]))
def slice_list(input):
    ans = []
    for x in input:
        ans.append(x[0])
    return ans

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM