找到列表的最小索引

时间:2016-11-13 06:50:27

标签: python list indexing min

大家好我需要帮助创建一个函数,该函数将找到包含字符串列表和整数列表的列表的最小索引。现在我可以让函数找到整数或字符串列表的最小索引,但不能同时找到两者。

def find_index_of_min(L):
    """
    Parameter: a list L
    Returns: the index of the minimum element of the list
        (returns None if the list is empty)
    """


    if L == []:
        return None
    elif L == str:
        min = 'Z'
        for i in range(len(L)):
            if L[i] < min:
                min = L[i]
                min_index = i
        return min_index
    elif L == int:
        min = float('inf')
        for i in range(len(L)):
            if L[i] < min:
                min = L[i]
                min_index = i
        return min_index

import sys
import math

def main():
    """ Read and print a file's contents. """

    # filename = str(input('Name of input file: '))
    # string = readfile(filename)
    # print()
    # print('The original list of cities is:')
    # for i in range(len(string)):
    # print(i, ':', string[i], sep="")

    print(find_index_of_min([]))
    print(find_index_of_min([3, 2, 1, 0]))
    print(find_index_of_min(['A', 'Z', 'Y', 'B']))
    print(find_index_of_min(['B', 'A', 'Z', 'Y']))

main()

2 个答案:

答案 0 :(得分:1)

您需要将L == intL == str(总是将其评估为False)替换为以下内容:

all(isinstance(item, str) for item in L)  # L == str
all(isinstance(item, int) for item in L)  # L == int

答案 1 :(得分:0)

你可以试试这个:

有一个函数可以检查里面的元素是数字还是字符串。

def isNumber(s): # Helper function to check if it is a Number or a string
    try:
        float(s)
        return True
    except ValueError:
        return False

def find_index_of_min(L):
    """
    Parameter: a list L
    Returns: the index of the minimum element of the list
        (returns None if the list is empty)
    """

    if L == []:
        return None
    elif isNumber(L[0]):
        min = float('inf')
        for i in range(len(L)):
            if L[i] < min:
                min = L[i]
                min_index = i
        return min_index
    else:
        min = 'Z'
        for i in range(len(L)):
            if L[i] < min:
                min = L[i]
                min_index = i
        return min_index


import sys
import math

def main():
    """ Read and print a file's contents. """

    # filename = str(input('Name of input file: '))
    # string = readfile(filename)
    # print()
    # print('The original list of cities is:')
    # for i in range(len(string)):
    # print(i, ':', string[i], sep="")

    print(find_index_of_min([]))
    print(find_index_of_min([3, 2, 1, 0]))
    print(find_index_of_min(['A', 'Z', 'Y', 'B']))
    print(find_index_of_min(['B', 'A', 'Z', 'Y']))

main()