Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字典优化了这个脚本_Python - Fatal编程技术网

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很乐意帮忙。如果有帮助的话,考虑接受答案(左边的记号)。