列表中的Python列表

时间:2015-01-25 05:57:56

标签: python

我有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)

8 个答案:

答案 0 :(得分:1)

假设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)

答案 1 :(得分:1)

感谢所有帮助。我能够以更少的努力获得理想的结果。以下是我的最终代码。希望大家都同意:

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)

答案 2 :(得分:0)

通过使用enumerate迭代子列表同时跟踪索引并使用每个子列表的.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" ) )

答案 3 :(得分:0)

使用index功能,如上所述[{3}}:

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

答案 4 :(得分:0)

以下功能将有所帮助:

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)  

如果您要打印该项目的所有实例,请删除&#39; return None&#39;在最里面的循环中的语句,添加一个found值,每当找到该项的第一个实例时,该值设置为1,并在结尾处添加以下语句:

if (found == 0):
    print("The item does not exist.")
    return None

答案 5 :(得分:0)

您的代码很难阅读并且非常冗余。

  1. **不要** 使用function作为功能名称,它是内置类型
  2. length = int(len(master_list))重复,使用len(master_list),len将返回一个int,无需转换它。
  3. 您应该使用for循环而不是while,而使用枚举器而不是计数器。
  4. 您的变量名称太长
  5. 检查你的缩进,它们应该是4个空格,你的用法不匹配。
  6. 使用字符串格式(%)而不是使用逗号打印
  7. 避免长线,每行最多120个字符。
  8. 无需将所有内容都放在新变量中。
  9. 这里的代码相同。

    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")
    

    输出:

    Master List has 2 sub-lists.
    
    The item you are searching for is 'Tomato'.
        Found at sub-list 1 in index position 1
    

答案 6 :(得分:0)

一些观察结果:

您需要缩进代码。虽然通常不需要循环,特别是对于这样的情况(例如,您只是尝试遍历列表以匹配项目)。

查看我在这里使用的一些函数:例如,format将帮助清除在需要在字符串中表达多个变量时使用的语法。没有必要,但在某些情况下,这将是非常有益的。

在使用enumerate时,另请查看for loops以获取项目本身的索引。

最后,请查看PEP8,了解有关样式和格式的一些指导。简单和简短的变量名称总是最好的。只要它仍然清楚地表达了数据类型。

 # 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))

输入

searchString = "Tomato"
searchItem(searchString)

<强>输出

"The item you searched for is Tomato. It's in the grocery list with an index of 1"

输入

searchString = "banana"
searchItem(searchString)

<强>输出

'The item you searched for ("banana") was not found.'

答案 7 :(得分:0)

最简单的方法是:

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)

样本

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.'