我有 1 个主列表,它基于 2 个子列表。我想创建一个带有“search_value”参数的函数,并希望打印“search_value”项的索引位置,包括子列表的列表索引。
示例:
grocery = ["Juice", "Tomato", "Potato", "Banana", "Milk", "Bread"]
clothes = ["Shirt", "Pant", "Jacket", "Sweater", "Hat", "Pajama", "T-Shiraz", "Polo"]
master_list = [grocery, clothes]
预期结果:
"The Item You Searched For is", search_value, ". It is in the first/second list with index position of:", index #
我是Python新手并且已经编写了工作代码。只是想知道如何以更少的努力做到这一点
def function(in_coming_string_to_search):
grocery = ["Juice", "Tomato", "Potato", "Banana", "Milk", "Bread"]
clothes = ["Shirt", "Pant", "Jacket", "Sweater", "Hat", "Pajama", "T-Shiraz", "Polo"]
master_list = [grocery, clothes]
length = int(len(master_list))
print master_list, "List has:", length, "list items", '\n'
to_do_list_first_array_index = 0
counter = 0
list_one_length = int(len(master_list[0]))
while counter < list_one_length:
for a in master_list[to_do_list_first_array_index]:
# print a
if a == in_coming_string_to_search:
print "The Item You Searched For is", in_coming_string_to_search, ". It is in the first list with index position of:", counter
counter = counter + 1
to_do_list_second_array_index = 1
counter2 = 0
list_two_length = int(len(master_list[1]))
while counter2 < list_two_length:
for b in master_list[to_do_list_second_array_index]:
if b == in_coming_string_to_search:
print "The Item You Searched For is", in_coming_string_to_search, ". It is in the second list with index position of:", counter2
counter2 = counter2 + 1
if __name__ == '__main__':
string_to_search = "Tomato"
function(string_to_search)
最佳答案
怎么样(假设master_list
及其子列表在全局范围内在此之前一次性定义):
def search(needle):
for i, sublist in enumerate(master_list):
where = sublist.find(in_coming_string_to_search)
if where == -1: continue
print "The Item You Searched For is", needle
print "It is in the {} sublist, at {}".format(nd(i), where)
return
print "Could not find {} anywhere".format(needle)
ordinals = "first", "second", "third", "fourth", "fifth"
def nd(i):
if i<len(ordinals): return ordinals[i]
return "{}th".format(i)
关于Python 列表中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28133696/