Python字符串比较最小/最大str

Python字符串比较最小/最大str,python,string,Python,String,我有一串日期的清单。比如说, x = ['2000-01-01', '2001-01-01', '2002-01-01'] def filter_str(x, lower_bound = '', upper_bound = ''): if lower_bound: x = [y for y in x if y > lower_bound] if upper_bound: x = [y for y in x if y < upper_b

我有一串日期的清单。比如说,

x = ['2000-01-01', '2001-01-01', '2002-01-01']
def filter_str(x, lower_bound = '', upper_bound = ''):
    if lower_bound:
        x = [y for y in x if y > lower_bound]
    if upper_bound:
        x = [y for y in x if y < upper_bound]
    return x
我想用可选的下限和上限过滤这些字符串。我可以使用if语句实现它。比如说,

x = ['2000-01-01', '2001-01-01', '2002-01-01']
def filter_str(x, lower_bound = '', upper_bound = ''):
    if lower_bound:
        x = [y for y in x if y > lower_bound]
    if upper_bound:
        x = [y for y in x if y < upper_bound]
    return x
对于我的例子,列表中的所有字符串都以一个数字开头,因此我猜
'a'
比列表中的任何字符串都大。但是,如果我的列表对任何类型的字符串都更一般,那么是否有一个最大的字符串


谢谢

> P>你可以让<强>默认输入远离日期,考虑如下:

import datetime

x = ['2000-01-01', '2001-01-01', '2002-01-01']
datefmt = "%Y-%m-%d" # The dateformat used to parse the dates

# This code can live for 180+ years, YAY! (2019-02-26)
def filter_str(x, lower_bound='1900-01-01', upper_bound='2199-12-31'):

  lb = datetime.datetime.strptime(lower_bound, datefmt)
  ub = datetime.datetime.strptime(upper_bound, datefmt)

  return [y for y in x if lb < datetime.datetime.strptime(y, datefmt) < ub]

out = filter_str(x, lower_bound='2000-02-01', upper_bound='2003-01-01')
print(out)
注意:此代码可以使用一些输入检查您是否传递了有效日期


内置的
filter
函数将
None
视为始终返回
True
的“函数”

from functors import partial
from operators import lt, gt

def filter_dates(x, lower_bound=None, upper_bound=None):
    lb = None if lower_bound is None else partial(lt, lower_bound)
    ub = None if upper_bound is None else partial(gt, upper_bound)

    return filter(lb, filter(ub, x)) 

(请注意,这将适用于字符串或
date
对象;只需传递相应类型的上下限即可。)

您的输入是字符串列表,但它们表示日期。最好使用Python中包含的datetime库。datetime中是否有最大/最小的日期?这可能行得通。我使用字符串是因为我认为不需要转换为datetime。我做的唯一一件事就是比较,在这个字符串格式中可以正常工作。抛开10k年的问题不谈,你可以使用
9999-99-99
。最小的时间通常是
1970-01-01
1970-01-01
不是最小的可表示日期时间对象,它只是
0
unix时间。像这样输入datetime对象是完全有效的:
datetime.datetime(1960,1,1)
您不能在1970年之前的datetime对象上使用
timestamp()
方法。谢谢!您将如何验证输入?如果格式不正确,strtime将引发错误。“这还不够吗?”蒂姆:这当然够了。您的代码在这一点上就会中断。取决于你想在哪里“部署”代码。我明白了。你是说可能有其他方法来处理输入,使其更平滑,而不是中断?@Tim我是说,如果有一些用户输入,可能会有错误,我只是想指出,我刚才编写的代码中没有错误处理程序。明白了。谢谢好主意!