簡體   English   中英

列表中的Python列表

[英]Python Lists within list

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

感謝您的所有幫助。 我能夠以更少的努力獲得期望的結果。 下面是我的最終代碼。 希望大家都同意:

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)

通過使用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" ) )

使用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

以下功能將有所幫助:

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)  

如果要打印該項目的所有實例,請在最內層的循環中刪除“ return None ”語句,並在找到該項目的第一個實例時添加一個設置為1的found值,並在末尾添加以下語句:

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

您的代碼很難閱讀,而且非常多余。

  1. **請勿**使用function作為函數名稱,它是內置類型
  2. length = int(len(master_list))是重復的,請使用len(master_list) ,len將返回一個int,無需進行轉換。
  3. 您應該使用for循環而不是while,並使用枚舉器而不是計數器。
  4. 您的變量名太長
  5. 還要檢查您的縮進,它們應該是4個空格,您用法不匹配。
  6. 使用字符串格式( % )而不是用逗號打印
  7. 避免排長行,每行最多120個字符。
  8. 無需將所有內容放入新變量中。

這是相同的代碼。

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

一些觀察:

您需要縮進代碼。 通常不需要while循環,尤其是在這種情況下(即,您只是試圖遍歷列表以匹配項)。

看一下我在這里使用的一些函數:例如,當需要在字符串中表達多個變量時, format將有助於清除使用的語法。 這不是必需的,但是在某些情況下,這將是非常有益的。

在使用for loops時,還請查看enumerate以獲取除項目本身之外的項目索引。

最后,看看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.'

最簡單的方法是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM