在键值对中搜索字符串 [重复]
Posted
技术标签:
【中文标题】在键值对中搜索字符串 [重复]【英文标题】:Search for a string in a key value pair [duplicate] 【发布时间】:2021-02-09 05:01:06 【问题描述】:尝试使用键 i['DBSnapshotIdentifier']
过滤 RDS 数据库名称。
示例数据库名称:db-test-709-au50-2020-10-17
或 db-test-uk10-2020-10-17
。
print('Deleting all DB Snapshots older than %s' % retentionDate)
for i in response['DBSnapshots']:
print(i['DBSnapshotIdentifier']) # gives: db-test-709-au50-2020-10-17
if (i['SnapshotCreateTime'] < retentionDate) and (i['DBSnapshotIdentifier'] == "*-au50*" or i['DBSnapshotIdentifier'] == "*-uk10*"):
print ('Deleting snapshot %s' % i['DBSnapshotIdentifier'])
试图弄清楚如何使用上面的 if 语句进行过滤。任何线索如何实现过滤器?蒂亚!
print(i)
给出:
u'MasterUsername': 'root', u'LicenseModel': 'postgresql-license', u'InstanceCreateTime': datetime.datetime(2017, 5, 23, 7, 52, 47, 355000, tzinfo=tzlocal()), u'Engine': 'postgres', u'VpcId': 'vpc-64b09', u'DBSnapshotIdentifier': 'db-test-709-au50-2020-10-17', u'AllocatedStorage': 5, u'Status': 'available', u'PercentProgress': 100, u'DBSnapshotArn': 'arn:aws:rds:eu-west-1:754878741835:snapshot:db-test-709-au50-2020-10-17', u'EngineVersion': '9.5.4', u'ProcessorFeatures': [], u'OptionGroupName': 'default:postgres-9-5', u'SnapshotCreateTime': datetime.datetime(2017, 5, 23, 8, 9, 24, 683000, tzinfo=tzlocal()), u'AvailabilityZone': 'eu-west-1a', u'StorageType': 'standard', u'Encrypted': False, u'IAMDatabaseAuthenticationEnabled': False, u'DbiResourceId': 'db-KQBQVZRNHHGHHJKIY3NZONZX5E', u'SnapshotType': 'manual', u'Port': 5432, u'DBInstanceIdentifier': 'db-test-709-au50'
【问题讨论】:
使用re.search。还要检查regular-expression 我回滚了您最近的编辑,因为它 (a) 将其变成了副本,并且 (b) 使某人刚刚发布的答案无效。 你不需要正则表达式;if "-au50" in i['DBSnapshotIdentifier']
【参考方案1】:
您可以在这里尝试这种方法:
import re
import functools
def identifierFilter(identifier, patterns):
return functools.reduce(lambda a,b : a or b,
map(lambda pattern: pattern in identifier, patterns))
def snapshotFilter(ele, params):
return (ele['SnapshotCreateTime'] < params["retentionDate"])
and identifierFilter(ele["DBSnapshotIdentifier"], params["dbIdentifierPattern"])
snapshotParams =
"retentionDate": retentionData,
"dbIdentifierPattern": ["-au50-", "-uk10-"]
snapshotsToDelete = filter(lambda ele: snapshotFilter(ele, snapshotParams), response['DBSnapshots'])
print('Deleting all DB Snapshots older than %s' % retentionDate)
for snapshot in snapshotsToDelete:
print ('Deleting snapshot %s' % snapshot['DBSnapshotIdentifier'])
# Bonus: Write tests for the above!
【讨论】:
@Don 不幸的是,OP 更改了问题的全部内容***.com/posts/64545580/revisions? 哦,我没注意到。我重新打开并回滚了 OP 的编辑。以上是关于在键值对中搜索字符串 [重复]的主要内容,如果未能解决你的问题,请参考以下文章