Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找列表列表中的所有元素位置_Python - Fatal编程技术网

Python 查找列表列表中的所有元素位置

Python 查找列表列表中的所有元素位置,python,Python,假设l=[[1,2,3],[3,4,5],[5,6]],有没有一种方法可以返回一个列表,该列表包含l中3的所有位置;i、 e.返回[2,3]。我编写的示例代码是: def pos_in_lists(seq, elem): while i < len(seq): elem_pos = seq[i].index(elem) return [elem_pos] def pos_in_列表(seq,elem): 而我

假设l=[[1,2,3],[3,4,5],[5,6]],有没有一种方法可以返回一个列表,该列表包含l中3的所有位置;i、 e.返回[2,3]。我编写的示例代码是:

def pos_in_lists(seq, elem):
    while i < len(seq):
        elem_pos = seq[i].index(elem)
        return [elem_pos]
def pos_in_列表(seq,elem):
而我
当我运行它时,它只返回2,这不是我想要的结果。我犯了什么错?还有,有没有更简单的方法来解决我的问题

  • 您需要在每个循环中增加“i”

  • “return”强制循环退出。这应该在代码末尾的循环之外


  • 您的代码只返回包含一个元素的列表(
    return[elem\u pos]
    )。您需要在循环外部有一个列表变量(
    result
    ),以便通过附加到该列表来跟踪以前列表的结果

    def pos_in_lists(seq, elem):
        result = []
        i = 0
        while i < len(seq):
            if elem in seq[i]:
                elem_pos = seq[i].index(elem)
                result.append(elem_pos)
            i += 1
        return result
    

    根据我对这个问题的理解,给定列表l=[[1,2,3],[3,4,5],[5,6]],如果我们必须找到3,输出列表应该是[2,0]

    提供的代码中存在以下错误:

    • 代码不起作用,因为在使用它之前,您的方法中没有定义i
    • 我们需要存储列表中存在的所有3个值的位置,因此我们需要有一个列表,其中存储列表中可以找到的3的所有位置。一旦找到一个值,您就返回了结果。因此,您只能得到2
    • seq[i]。如果列表中没有3,索引(elem)将抛出值错误

      解决方案

      def位置列表(序号,要素):

      位置列表(l,3)

    结果将是[2,0]

    我们也可以使用列表理解:

    def pos_in_lists(seq, elem):
        return [innerList.index(elem) for innerList in seq if elem in innerList]
    

    既然
    [3,4,5]
    中的3在索引0处,那么结果不应该是
    [2,0]
    吗?是的,这是我的错误。
    res = []
    for innerList in seq:
        if elem in innerList:
            res.append(innerList.index(elem))
    return res
    
    def pos_in_lists(seq, elem):
        return [innerList.index(elem) for innerList in seq if elem in innerList]