这是leecode的第17题,代码如下:
class Solution:
dt = {'2':'abc', '3':'def', '4':'ghi', '5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'}
def letterCombinations(self, digits: str) -> list:
if len(digits) == 0:
return []
from itertools import product
chars = [self.dt[i] for i in digits]
return [''.join(i) for i in product(*chars)]
代码没啥好说的,代码中的pythonic的操作可以好好说说。
Python itertools.product() 操作
目前有一字符串 s = "['a', 'b'],['c', 'd']",想把它分开成为两个列表:
list1 = ['a', 'b']
list2 = ['c', 'd']
之后使用 itertools.product() 求笛卡尔积,应该写成:
for i in itertools.product(list1, list2):
print i
结果为:
('a', 'c')
('a', 'd')
('b', 'c')
('b', 'd')
然而使用 eval(s) 获得的是一个元组。product 的参数如果是元组则一定会报错(product 的参数是两个列表,每个列表中的元素数量不定)。怎么破?
Python 星号 * 解包技巧
其实只差一个 * 而已。* 是 Python 中一个赋值的技巧,叫做解包。相信很多人都见过 def func(*args, **kwargs) 这种写法,在函数中,* 代表不定个数的参数,以 tuple 的方式传入,** 则是以 dict 的方式。在使用函数的时候,也可以有类似的方法,调用 func(*args) 函数时,相当于把一个元组 args 拆开,当成参数传进函数中。只是这样做要小心的是,args 中含有的元素数量及类型必须跟该函数定义一致,否则会报 SyntaxError: invalid syntax 语法错误。
例如,在这道题中,就可以写成:
for i in itertools.product(*eval(s)):
print i
就可以出来结果了。
这个问题用到的三个技巧:
itertools.product()求笛卡尔积。itertools这个模块中有相当多的牛逼闪闪的数学算法,比如全排列函数permutations,组合函数combinations等等,有时候想要一个数学类的函数又不想自己写,可以在这里找找,没准有惊喜。eval()字符串求值。eval和exec这两个 Python 中的逆天函数,强大到让人不太放心其安全性。*解包。上面已经解释过了,其实用到的场合感觉挺有限的,有印象即可,能在无路可走的时候灵光一现就好,别太指望它给你的程序带来多大好处。
参考
https://oldtang.com/6992.html
https://blog.youkuaiyun.com/qdPython/article/details/110085701
本文解析了LeetCode第17题的解决方案,并详细介绍了Python中的itertools.product()函数如何用于生成字符串的所有可能组合,同时讲解了eval()函数与解包技巧的应用。

被折叠的 条评论
为什么被折叠?



