Python字典优化了这个脚本
我有一个字符串,比如Python字典优化了这个脚本,python,Python,我有一个字符串,比如rdb\u master\u mongodb,其中rdb\u是固定的,master是一个数据库名称,可以是任何东西,mongodb可以是mysql、mongodb、postgres、mssql或bdb中的一个。我需要从字典中获取该字符串的值,该字典的值位于myDict[master][mongodb]中。为了得到这个,我需要拆分字符串rdb\u master\u mongodb,并获得master和mongodb的值。我不能使用split,因为有时字符串会变成rdb\u ma
rdb\u master\u mongodb
,其中rdb\u
是固定的,master
是一个数据库名称,可以是任何东西,mongodb
可以是mysql
、mongodb
、postgres
、mssql
或bdb
中的一个。我需要从字典中获取该字符串的值,该字典的值位于myDict[master][mongodb]
中。为了得到这个,我需要拆分字符串rdb\u master\u mongodb
,并获得master
和mongodb
的值。我不能使用split,因为有时字符串会变成rdb\u master\u test\u mongodb
。因此,我必须使用endswith
来获取准确的密钥。但是,endswith
在列表上不起作用
我必须从元组中获取匹配的元组值。现在我这样做:
import re
name = 'rdb_master_mongodb'
s = re.sub('rdb_', "", name)
VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb')
(a, b, c, d, e) = VALID_DB
if s.endswith(a):
db = a
if s.endswith(b):
db = b
if s.endswith(c):
db = c
if s.endswith(d):
db = d
if s.endswith(e):
db = e
db_name = re.sub('_'+db, "", s)
print db_name+" is "+db
有更好的方法吗?如果
名称的格式始终相同,您可以先将其拆分为多个部分:
db = name.rsplit('_', 1)[1]
if db not in VALID_DB:
raise ValueError('Incorrect DB name: %s' % db)
rdb, temp = name.split('_', 1)
master, db = temp.rsplit('_', 1)
然后检查db
是否有效:
VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb')
if db in VALID_DB:
...
然后使用这三个变量rdb、master、db来构建所需的字符串。因此,如果我能很好地理解您的意思,那么我会尝试:
>>> VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb')
>>> name = 'rdb_master_mongodb'
>>> db_name = [db for db in VALID_DB if name.endswith(db)][0]
>>> db_name
'mongodb'
>>> name_test = 'rdb_master_test_mongodb'
>>> db_name = [db for db in VALID_DB if name_test.endswith(db)][0]
>>> db_name
'mongodb'
rdb,master,db='rdb\u master\u test\u mongodb'.split(“')
给出了ValueError:太多的值无法解包
。我想你应该拆分两次。@LevLevitsky-你说得对,然后我们必须拆分两次。答案已更新。.endswith
忽略\uu
的位置,并接受的“xxx\u badmysql”。endswith('mysql')
也是。@bubby很乐意帮忙。如果有帮助的话,考虑接受答案(左边的记号)。