Find maximum int value from list which contain both str and int python

前端 未结 5 1780

Looking to find max from the combine list as follows:

[\'filename1\', 1696, \'filename2\', 5809,....]

I have tried following:<

相关标签:
5条回答
  • 2020-12-11 14:51

    The same isinstance idea can be applied to a filter:

    f = ['filename1', 1696, 'filename2', 5809]
    max(filter(lambda i: isinstance(i, int), f))
    

    Also, if you need to include more than one data type in your comparison, e.g.: floats, you can simple use a tuple to validate the the data to be compared:

    max(filter(lambda i: isinstance(i, (int, float)), f))
    
    0 讨论(0)
  • 2020-12-11 14:53

    If your real data also has alternating strings and integers, like your example, you can just iterate in steps of size 2, starting with the second element:

    values = ['filename1', 1696, 'filename2', 5809, ...]
    max(values[1::2])
    # 5809
    

    Note that this slicing creates a new list (so depending on the size of the original list it might be very large).

    0 讨论(0)
  • 2020-12-11 14:59

    Use list comprehension with isinstance to extract the int and then use max.

    Ex:

    f = ['filename1', 1696, 'filename2', 5809]
    print(max([i for i in f if isinstance(i, int)]))
    #or generator
    print(max((i for i in f if isinstance(i, int))))    #Better Option
    

    Output:

    5809
    5809
    
    0 讨论(0)
  • 2020-12-11 15:07

    You can also use try...except clause.

    lst = ['filename1', 1696, 'filename2', 5809]
    numbers = []
    
    for item in lst:
        try:
            numbers.append(int(item))
        except ValueError:
            pass # Ignore items which are not numbers
    
    print(max(numbers))
    # 5809
    
    0 讨论(0)
  • 2020-12-11 15:09

    max() expects iterable with comparable values. You should ignore string first from the list and then use max() on it.

    Use list comprehension to only consider integer values

    file_data = ['filename1', 1696, 'filename2', 5809,....]
    max([elem for elem in file_data if isinstance(elem, int)])
    

    If you are expecting float values as well, you can update it as:

    max([elem for elem in file_data if not isinstance(elem, str)])
    
    0 讨论(0)
提交回复
热议问题