簡體   English   中英

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

[英]find all element positions within a list of lists

鑒於 l = [[1,2,3], [3,4,5],[5,6]],是否有一種方法可以返回一個列表,該列表包含 l 內 3 的所有位置; 即返回[2,3]。 我寫的一個示例代碼是:

def pos_in_lists(seq, elem):
    while i < len(seq):
        elem_pos = seq[i].index(elem)
        return [elem_pos]

當我運行它時,它只返回 2,這不是我想要的結果。 我的錯誤是什么? 另外,有沒有更簡單的方法來解決我的問題?

  1. 您需要在每個循環中增加“i”

  2. "return" 強制循環退出。 那應該在代碼末尾的循環之外。

您的代碼僅返回一個包含一個元素的列表( return [elem_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

另一個更簡單的選擇是使用列表推導

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

根據我對問題的理解,給定列表 l = [[1,2,3], [3,4,5],[5,6]] 如果我們必須找到 3,則 output 列表應該是 [2 ,0]。

提供的代碼中存在以下錯誤:

  • 該代碼不起作用,因為在使用之前未在您的方法中定義 i。
  • 我們需要存儲列表中存在的所有 3 個值的位置,因此我們需要一個列表,其中存儲我們可以在列表中找到的 3 的所有位置。 一旦找到一個值,您就返回了結果。 因此,您只得到 2 個。
  • 如果 3 不在列表中,seq[i].index(elem) 將拋出值錯誤。

    解決方案

    def pos_in_lists(seq, elem):

     res = [] for innerList in seq: if elem in innerList: res.append(innerList.index(elem)) return res

    pos_in_lists(l,3)

結果將是 [2,0]

我們也可以使用列表推導:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM