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

时间:2019-02-26 21:11:55

标签: python string

我有一个日期字符串列表。例如,

x = ['2000-01-01', '2001-01-01', '2002-01-01']

我想用可选的上下限过滤这些字符串。我可以使用if语句实现它。例如,

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

我想知道是否有更优雅的方法来做到这一点?


我发现空字符串('')小于任何非空字符串。是否有一个比每个非空字符串都大的字符串?

这样,我可以将filter_str简化为

def filter_str(x, lower_bound = '', upper_bound = LARGEST_STR):
    return [y for y in x if y > lower_bound and y < upper_bound]

对于我来说,列表中的所有字符串都以数字开头,所以我猜'a'大于列表中的任何字符串。但是,如果我的列表对任何类型的字符串都比较笼统,是否有最大的字符串?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以将默认输入的日期设为较远的日期,请考虑以下事项:

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)

返回:

['2001-01-01', '2002-01-01']
  

注意:此代码可以使用一些输入检查来确定您传递的有效日期。

答案 1 :(得分:1)

内置的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对象;只需传递适当类型的上下限。)