iTesting,爱测试,爱分享
上次分享了一道有趣的字符串面试题,今天我们再重新审视下这道题,并借此机会了解下python库的强大。
上次的原题是这样的:
我原来的解决方法如下:
def count_s(s):
if len(s)<=0 or not isinstance(s, str):
return
base = s[0]
result = []
count = 1
for i in s[1:]:
if i == base:
count +=1
else:
result.append(base+str(count))
count =1
base = i
result.append(base + str(count))
return result
print(count_s('abbcccdxt'))
后来有同学在评论中指出,有更好的解决方案,我们使用下看看。
from collections import OrderedDict
def count_s(s):
if len(s)<=0 or not isinstance(s, str):
return
d = OrderedDict()
for _ in s:
if _ in d.keys():
d.update({_:d[_]+1})
else:
d.update({_: d.setdefault(_, 1)})
return list(map(lambda x: x +str(d[x]), d))
print(count_s('abbcccdxt'))
OrderedDict
The OrderedDict API is substantially the same as regular dictionaries but will iterate over keys and values in a guaranteed order depending on when a key was first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end. Usage
d = OrderedDict()
d['parrot'] = 'dead'
d['penguin'] = 'exploded'
d.update({'foo': 'bar'})
print(d.items())
#output:
odict_items([('parrot', 'dead'), ('penguin', 'exploded')])
dict.setdefault(key, default=None)
如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值
map(function, iterable, …)
map() 会根据提供的函数对指定序列做映射。 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
from collections import OrderedDict
def count_s(s):
if len(s)<=0 or not isinstance(s, str):
return
d = OrderedDict()
for _ in s:
if _ in d.keys():
d.update({_:d[_]+1})
else:
d.update({_: d.setdefault(_, 1)})
return list(map(lambda x: d[x]*x, d))
print(count_s('abbcccdxt'))
from collections import OrderedDict
def count_s(s):
if len(s)<=0 or not isinstance(s, str):
return
d = OrderedDict()
for _ in s:
if _ in d.keys():
d.update({_:d[_]+1})
else:
d.update({_: d.setdefault(_, 1)})
return list(map(lambda x: x*d[x],filter(lambda x: True if d[x]==3 else False , d)))
print(count_s('abbcccdxt'))
filter(function, iterable)
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
from collections import Counter
def count_s(s):
if len(s)<=0 or not isinstance(s, str):
return
return [s[number:number+3] for number in range(len(s)-2)]
print(Counter(count_s('abccbbcc')))
def count_s(s):
if len(s) <= 0 or not isinstance(s, str):
return
r = []
for i in range(len(s)):
for item in [s[number:number + i+1] for number in range(len(s) - i)]:
r.append(list(item))
return r
print((count_s('123')))
怎么样,这一圈下来明白python的标准库有多强大了吧, 作为一个pythoner,一定要足够pythonic.