dict1={'s1':[1,2,3],'s2':[4,5,6],'a':[7,8,9],'s3':[10,11]}
我怎样才能得到's'键的所有值?喜欢dict1['s*']
得到的结果是dict1['s*']=[1,2,3,4,5,6,10,11]
dict1={'s1':[1,2,3],'s2':[4,5,6],'a':[7,8,9],'s3':[10,11]}
我怎样才能得到's'键的所有值?喜欢dict1['s*']
得到的结果是dict1['s*']=[1,2,3,4,5,6,10,11]
>>> [x for d in dict1 for x in dict1[d] if d.startswith("s")]
[1, 2, 3, 4, 5, 6, 10, 11]
或者,如果它需要是一个正则表达式
>>> regex = re.compile("^s")
>>> [x for d in dict1 for x in dict1[d] if regex.search(d)]
[1, 2, 3, 4, 5, 6, 10, 11]
您在这里看到的是嵌套列表理解。相当于
result = []
for d in dict1:
for x in dict1[d]:
if regex.search(d):
result.append(x)
因此,它的效率有点低,因为正则表达式的测试过于频繁(并且元素被一一附加)。所以另一个解决方案是
result = []
for d in dict1:
if regex.search(d):
result.extend(dict1[d])
>>> import re
>>> from itertools import chain
def natural_sort(l):
# http://stackoverflow.com/a/4836734/846892
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(l, key = alphanum_key)
...
使用全局模式,'s*'
:
>>> import fnmatch
def solve(patt):
keys = natural_sort(k for k in dict1 if fnmatch.fnmatch(k, patt))
return list(chain.from_iterable(dict1[k] for k in keys))
...
>>> solve('s*')
[1, 2, 3, 4, 5, 6, 10, 11]
使用regex
:
def solve(patt):
keys = natural_sort(k for k in dict1 if re.search(patt, k))
return list(chain.from_iterable( dict1[k] for k in keys ))
...
>>> solve('^s')
[1, 2, 3, 4, 5, 6, 10, 11]
我在下面尝试了希望它对您有所帮助,方法是获取字典的键,然后如果键的第一个索引是您的字符开头,则使用键字典列表扩展列表。
n='s' # your start with character
result=[] # your output
for d in dict1.keys():
if n == d[0]:
result.extend(dict1[d])
print result