我们有一个包含子列表的主列表,你想创建一个函数来查找特定元素。该函数应该返回该元素在主列表中的位置以及它所在的子列表。
例如,如果主列表如下:
grocery = ["Juice", "Tomato", "Potato", "Banana", "Milk", "Bread"]
clothes = ["Shirt", "Pant", "Jacket", "Sweater", "Hat", "Pajama", "T-Shiraz", "Polo"]
master_list = [grocery, clothes]
如果我们要查找元素“Tomato”,那么函数应该返回以下结果:
The Item You Searched For is Tomato. It is in the first list with index position of: 1
2、解决方案
有几种方法可以解决这个问题。一种方法是使用内置的 enumerate()
函数来循环遍历主列表中的子列表。然后,我们可以使用 find()
方法来在每个子列表中查找元素。如果元素存在,我们可以使用 index()
方法来获取元素在子列表中的位置。最后,我们可以使用 print()
函数来输出结果。
以下是一个使用这种方法实现的函数:
def find_item(master_list, item_to_search):
"""
Finds an item in a nested list and returns its index position.
Args:
master_list: The nested list to search.
item_to_search: The item to search for.
Returns:
A tuple containing the index of the item in the master list and the index of the item in the sublist.
"""
for index, sublist in enumerate(master_list):
try:
item_index = sublist.index(item_to_search)
return index, item_index
except ValueError:
pass
return -1, -1
if __name__ == "__main__":
grocery = ["Juice", "Tomato", "Potato", "Banana", "Milk", "Bread"]
clothes = ["Shirt", "Pant", "Jacket", "Sweater", "Hat", "Pajama", "T-Shiraz", "Polo"]
master_list = [grocery, clothes]
item_to_search = "Tomato"
index, sublist_index = find_item(master_list, item_to_search)
if index == -1:
print("Item not found")
else:
print("The Item You Searched For is", item_to_search, ". It is in the", index, "list with index position of:", sublist_index)
另一种方法是使用 itertools.product()
函数来生成所有可能的子列表与元素的组合。然后,我们可以使用 filter()
函数来过滤掉不包含元素的组合。最后,我们可以使用 next()
函数来获取第一个组合,并使用 index()
方法来获取元素在子列表中的位置。
以下是一个使用这种方法实现的函数:
from itertools import product
def find_item(master_list, item_to_search):
"""
Finds an item in a nested list and returns its index position.
Args:
master_list: The nested list to search.
item_to_search: The item to search for.
Returns:
A tuple containing the index of the item in the master list and the index of the item in the sublist.
"""
for index, sublist in enumerate(master_list):
for sublist_index, item in enumerate(sublist):
if item == item_to_search:
return index, sublist_index
return -1, -1
if __name__ == "__main__":
grocery = ["Juice", "Tomato", "Potato", "Banana", "Milk", "Bread"]
clothes = ["Shirt", "Pant", "Jacket", "Sweater", "Hat", "Pajama", "T-Shiraz", "Polo"]
master_list = [grocery, clothes]
item_to_search = "Tomato"
index, sublist_index = find_item(master_list, item_to_search)
if index == -1:
print("Item not found")
else:
print("The Item You Searched For is", item_to_search, ". It is in the", index, "list with index position of:", sublist_index)
这两种方法都可以用来解决这个问题。哪一种方法更好取决于具体情况。如果主列表很大,那么使用 enumerate()
函数可能会更好,因为它的时间复杂度是 O(n),而 product()
函数的时间复杂度是 O(n^2)。然而,如果子列表很长,那么使用 product()
函数可能会更好,因为它的空间复杂度是 O(n),而 enumerate()
函数的空间复杂度是 O(n^2)。