[英]Python Lists within list
I have 1 master list which is based on 2 child lists. 我有1个基于2个子列表的主列表。 I want to create a function with "search_value" parameter & would like to print the index position of the "search_value" item including the list index of child list.
我想使用“ search_value”参数创建一个函数,并希望打印“ search_value”项的索引位置,其中包括子列表的列表索引。
Example: 例:
grocery = ["Juice", "Tomato", "Potato", "Banana", "Milk", "Bread"]
clothes = ["Shirt", "Pant", "Jacket", "Sweater", "Hat", "Pajama", "T-Shiraz", "Polo"]
master_list = [grocery, clothes]
Expected result : 预期结果 :
"The Item You Searched For is", search_value, ". It is in the first/second list with index position of:", index #
I am new to python & have written the working code. 我是python的新手,并且已经编写了工作代码。 Just want to know how to do it with less effort
只想知道如何轻松地做到这一点
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)
What about (assuming master_list
and its sub-lists are defined once and for all in global scope before this): 怎么样(假设
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)
Thanks for all the help. 感谢您的所有帮助。 I am able to get the desired result with much less effort.
我能够以更少的努力获得期望的结果。 Below is my final code.
下面是我的最终代码。 Hope you guys all will agree:
希望大家都同意:
def two_dim_list(incoming_item_to_search):
my_list = [["Banana", "Apple", "Orange", "Grape", "Pear"], ["Book", "Pen", "Ink", "Paper", "Pencil"], ["Shirt", "Pant", "Jacket", "Hat", "Coat"]]
list_length = len(my_list)
counter = 0
while counter < list_length:
try:
index = my_list[counter].index(incoming_item_to_search)
if index >= 0:
print "found item", incoming_item_to_search, "at index:", index, "of", counter, "sublist"
except ValueError:
pass
counter = counter + 1
if __name__ == '__main__':
item_to_search = "Coat"
two_dim_list(item_to_search)
This can be condensed considerably by making use of enumerate
to iterate over sub-lists while keeping track of the index, and using the .index
method of each sub-list: 通过使用
enumerate
来迭代子列表同时跟踪索引,并使用每个子列表的.index
方法,可以.index
过程:
def FindInLists( listOfLists, searchTerm ):
for listIndex, subList in enumerate( listOfLists ):
if searchTerm in subList:
pos = subList.index( searchTerm )
print( "{term} found at position {pos} of list #{which}".format( term=repr( searchTerm ), pos=pos, which=listIndex ) )
return listIndex, pos
print( "{term} not found".format( term=repr( searchTerm ) ) )
return None, None
# test:
grocery = ["Juice", "Tomato", "Potato", "Banana", "Milk", "Bread"]
clothes = ["Shirt", "Pant", "Jacket", "Sweater", "Hat", "Pajama", "T-Shiraz", "Polo"]
master_list = [grocery, clothes]
print( FindInLists( master_list, "Hat" ) )
print( FindInLists( master_list, "Hats" ) )
Use the index
function, as mentioned here : 使用
index
功能,提到这里 :
try:
index1 = master_list[0].index(in_coming_string_to_search)
if index1 >= 0:
print "The Item You Searched For is", in_coming_string_to_search, ". It is in the first list with index position of:", index1
except ValueError:
pass
try:
index2 = master_list[1].index(in_coming_string_to_search)
if index2 >= 0:
print "The Item You Searched For is", in_coming_string_to_search, ". It is in the secpnd list with index position of:", index2
except ValueError:
pass
The following function will help: 以下功能将有所帮助:
def func(new_string):
grocery = ["Juice", "Tomato", "Potato", "Banana", "Milk", "Bread"]
clothes = ["Shirt", "Pant", "Jacket", "Sweater", "Hat", "Pajama", "T-Shiraz", "Polo"]
master_list = [grocery, clothes]
child_list_num = 1
counter = 0
for child_list in master_list:
for item in child_list:
if item == new_string:
print("The Item You Searched For is", new_string,
". It is in the chlid list "+ str(child_list_num) +
" with index position of:", counter)
return None
counter += 1
counter = 0
child_list_num += 1
print("The item does not exist.")
return None
if __name__ == '__main__':
item = "Sweater"
func(item)
If you want to print ALL the instances of the item, then remove the ' return None
' statement in the innermost loop, add a found
value that is set to 1 whenever the first instance of the item is found and the following statement at the end: 如果要打印该项目的所有实例,请在最内层的循环中删除“
return None
”语句,并在找到该项目的第一个实例时添加一个设置为1的found
值,并在末尾添加以下语句:
if (found == 0):
print("The item does not exist.")
return None
Your code is quite hard to read and very redundant. 您的代码很难阅读,而且非常多余。
function
as a function name, it's a built-in type function
作为函数名称,它是内置类型 length = int(len(master_list))
is repetitive, use len(master_list)
, len will return a int, no need to convert it. length = int(len(master_list))
是重复的,请使用len(master_list)
,len将返回一个int,无需进行转换。 %
) instead of printing with commas %
)而不是用逗号打印 Here's the same code. 这是相同的代码。
def find_string(target):
master_list = [
["Juice", "Tomato", "Potato", "Banana", "Milk", "Bread"],
["Shirt", "Pant", "Jacket", "Sweater", "Hat", "Pajama", "T-Shiraz", "Polo"]
]
print "Master List has %d sub-lists.\n" % len(master_list)
print "The item you are searching for is '%s'." % target
for list_index, sub_list in enumerate(master_list):
for item_index, item in enumerate(sub_list):
if item == target:
print "\tFound at sub-list %d in index position %d" % (list_index+1, item_index)
break
if __name__ == '__main__':
find_string("Tomato")
Output: 输出:
Master List has 2 sub-lists.
The item you are searching for is 'Tomato'.
Found at sub-list 1 in index position 1
You need to indent your code. 您需要缩进代码。 While loops are usually not needed, especially for situations like this (ie you are simply trying to loop over a list to match an item).
通常不需要while循环,尤其是在这种情况下(即,您只是试图遍历列表以匹配项)。
Look at some of the functions I'm using here: For example, format
will help clean the syntax being used when needing to express several variables inside a string. 看一下我在这里使用的一些函数:例如,当需要在字符串中表达多个变量时,
format
将有助于清除使用的语法。 It is not necessary, but in certain situations this will be greatly beneficial. 这不是必需的,但是在某些情况下,这将是非常有益的。
Also look at enumerate
to get the index of an item in addition to the item itself when using for loops
. 在使用
for loops
时,还请查看enumerate
以获取除项目本身之外的项目索引。
Finally, take a look at PEP8 for some guidelines on style and formatting. 最后,看看PEP8上有关样式和格式的一些准则。 Simple and short variable names are always best.
简单和简短的变量名始终是最好的。 As long as it still expresses the type of data clearly.
只要它仍然清楚地表示数据类型。
# In Python, you need to indent the contents of the function
# (the convention is 4 spaces)
def searchItem(searchString): # Avoid really long variable names.
grocery = [
"Juice", "Tomato", "Potato",
"Banana", "Milk", "Bread"
]
clothes = [
"Shirt", "Pant", "Jacket", "Sweater",
"Hat", "Pajama", "T-Shiraz", "Polo"
]
masterDict = {'grocery': grocery, 'clothes': clothes}
# No need to use int(). len() returns an int by default.
length = len(masterDict)
# Printing the master_list variable actually prints the list
# representation (and not the variable name), which is probably
# not what you wanted.
print 'master_dict has a length of {0}'.format(length), '\n'
itemInfo = None
for listType, subList in masterDict.iteritems():
for itemIndex, item in enumerate(subList):
if item == searchString:
itemInfo = {'listType': listType, 'itemIndex': itemIndex}
break
if itemInfo:
print ("The item you searched for is {0}. It's in the {1} "
"list with an index of {2}").format(
searchString, itemInfo['listType'], itemInfo['itemIndex'])
else:
print ('The item you searched for ("{0}") was not found.'
.format(searchString))
Input : 输入 :
searchString = "Tomato"
searchItem(searchString)
Output : 输出 :
"The item you searched for is Tomato. It's in the grocery list with an index of 1"
Input : 输入 :
searchString = "banana"
searchItem(searchString)
Output : 输出 :
'The item you searched for ("banana") was not found.'
Easiest way to do this will be: 最简单的方法是:
grocery = ["Juice", "Tomato", "Potato", "Banana", "Milk", "Bread"]
clothes = ["Shirt", "Pant", "Jacket", "Sweater", "Hat", "Pajama", "T-Shiraz", "Polo"]
master_list = [grocery, clothes]
def search(needle):
return_string = "The item you searched for is {}. It is in the {}{} list with index position of {}"
ordinals = {"1":"st", "2":"nd", "3":"rd"}
for lst_idx,sublst in enumerate(master_list, start=1):
try:
needle_idx = str(sublst.index(needle))
except ValueError:
continue
else:
lst_idx = str(lst_idx)
return return_string.format(needle,
lst_idx,
ordinals.get(lst_idx, 'th'),
needle_idx)
return "The item {} is not in any list.".format(needle)
DEMO 演示
In [11]: search("Juice")
Out[11]: 'The item you searched for is Juice. It is in the 1st list with index p
osition of 0'
In [12]: search("Pajama")
Out[12]: 'The item you searched for is Pajama. It is in the 2nd list with index
position of 5'
In [13]: search("Not existent")
Out[13]: 'The item Not existent is not in any list.'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.