简体   繁体   中英

Python Lists within list

I have 1 master list which is based on 2 child lists. 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.

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. 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):

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:

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 :

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:

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

Your code is quite hard to read and very redundant.

  1. **DO NOT** use function as a function name, it's a built-in type
  2. length = int(len(master_list)) is repetitive, use len(master_list) , len will return a int, no need to convert it.
  3. You should use for loops instead of while, and enumerator instead of a counter.
  4. Your variable names are too long
  5. Check your indentation too, they should be 4 spaces, you have mismatched of uses.
  6. use string formatting ( the % ) instead of printing with commas
  7. Avoid long lines, max to 120 chars per line.
  8. No need to put everything in new variables.

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

Some observations:

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

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

Finally, take a look at PEP8 for some guidelines on style and formatting. 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.'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM