你怎么知道子列表中元素的索引

时间:2016-12-03 15:04:11

标签: python list

您如何知道子列表中元素的索引? A similar question was asked here表示没有嵌套的列表

像这样:

3

当元素为output=[0][2] 时,我想成为输出:

let cubeData: [Float] = [1.1, 2.2, 3.3, 4.4]

let b = cubeData.withUnsafeBufferPointer { Data(buffer: $0) }

print(b as NSData)
// <cdcc8c3f cdcc0c40 33335340 cdcc8c40>

6 个答案:

答案 0 :(得分:3)

试试这个:

def get_sublist_index(lists, item):
    for sublist in lists:
        if item in sublist:
            return lists.index(sublist), sublist.index(item)

>>> L=[[1,2,3],[4,5,6]]
>>> get_sublist_index(L, 3)
(0, 2)

或者获得每件物品:

def get_sublist_index(lists, item):
    for sublist in lists:
        if item in sublist:
            yield lists.index(sublist), sublist.index(item)

制作generator

>>> L=[[1,2,3],[4,3,6]]
>>> get_sublist_index(L, 3)
<generator object get_sublist_index at 0x1056c5e08>
>>> [i for i in get_sublist_index(L, 3)]
[(0, 2), (1, 1)]

或者如果你不想要发电机:

def get_sublist_index(lists, item):
    outList = []
    for sublist in lists:
        if item in sublist:
            outList.append((lists.index(sublist), sublist.index(item)))
    return outList

>>> get_sublist_index(L, 3)
[(0, 2), (1, 1)]
>>> 

答案 1 :(得分:3)

L=[[1,2,3],[4,5,6],[2,3,4,5,3]]

a = 3

print([(i,j) for i,x in enumerate(L) if a in x for j,b in enumerate(x) if b == a])
#[(0, 2), (2, 1), (2, 4)]

使用列表理解,您可以挖掘并返回所有子值。如果你需要更深入,只需继续链接列表理解或编写一个函数来完成它。

答案 2 :(得分:2)

也许是这样的:

def find_sublist(outer, what):
    for i, lst in enumerate(outer):
        try:
            return i, lst.index(what)
        except ValueError:
            pass

实际上,output = [0][2]会抛出异常。不确定你的意思。你想要一个两元素的元组吗?我会假设你这样做。

你也可以使用更优雅的东西,比如

In [8]: [(i, sublist.index(3)) for i, sublist in enumerate(L) if 3 in sublist]
Out[8]: [(0, 2)]

In [9]: [(i, sublist.index(4)) for i, sublist in enumerate(L) if 4 in sublist]
Out[9]: [(1, 0)]

答案 3 :(得分:2)

使用numpy.wherenumpy.transpose方法的“单行”解决方案(初始输入数组已扩展为涵盖复杂案例):

 [[0 2]
  [1 1]]

输出:

 var start_time = dateTimePicker1.Text;
 var start_time_array = start_time.Split(':');
 var today = DateTime.Now;
 var trailer_count = Convert.ToInt32(tbTrailer_Needed.Text);
 var minutes_apart = Convert.ToDouble(tbTime_Between.Text);
 var calculated_start_time = new DateTime(today.Year, today.Month, 
     today.Day, Convert.ToInt16(start_time_array[0]), 
     Convert.ToInt16(start_time_array[1]), 00);

答案 4 :(得分:1)

对于需要索引和序列的任务,您应始终依靠enumerate

def find_index(l, val=3):
    # res holds results
    res = []
    # Go through every sublist in l 
    # index1 indicates which sublist we check
    for index1, sublist in enumerate(l):
        # Go through every item in sublist 
        # index2 indicates which item we check
        for index2, item in enumerate(sublist):
            # append to result if we find a match
            if item == val:
                res.append([index1, index2])
    return res

使用样本列表:

L = [[1, 2, 3], [4, 5, 6, 4, 3], [3, 3, 3]]

返回:

find_index(L)
[[0, 2], [1, 4], [2, 0], [2, 1], [2, 2]]

答案 5 :(得分:0)

考虑使用more_itertools.locate返回索引字典。

代码

import more_itertools as mit


def indices(iterable, item):
    """Return a dict of indices of all located items."""
    d = {}
    for i, sub in enumerate(iterable):
        val = list(mit.locate(sub, lambda x: x == item))
        if not val:
            continue
        d[i] = val

    return d

演示

给出浅层,嵌套的可迭代对象:

indices([[1, 2, 3], [5, 6, 7]], 3)
# {0: [2]}

indices([[1, 2, 3], [5, 6, 7], [2, 3, 3]], 3)
# {0: [2], 2: [1, 2]}

这里记录了多次出现。