一、作用及语法
-
作用:根据已有列表高效创建列表
-
语法:
-
[expression for iter_val in iterable]
- expression 指的是表达式,表达式中应对iter_val进行操作
- for iter_val in iterable的意思是,将列表iterable中的元素一一取出为iter_val
- 最终各个iter_val经过expression操作后得到的各个值作为新列表的元素
-
[expression for iter_val in iterable if cond_expr]
- if后面的cond_expr为真的话,才取出iter_val,比如:
-
13 >>>L = [ i**2 for i in range(1,11) if i >= 4 ]
14 >>>print L
15 [16, 25, 36, 49, 64, 81, 100]
二、Leetcode应用
17. Letter Combinations of a Phone Number
方法一、非递归
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if digits == '':
return []
dict = {'2': 'abc', '3': 'def',
'4': 'ghi','5': 'jkl', '6': 'mno',
'7': 'pqrs','8': 'tuv', '9': 'wxyz',
}
# 列表解析,不断输出字典中对应的键值到i,由i作为新的列表元素
cur = [i for i in dict[digits[0]]]
#之前是用digits的长度进行遍历,但其实可以直接用digits中的值进行遍历
#这样可以简化,直接用i就可以取字典中的值
for i in digits[1:]:
cur = [c+p for c in cur for p in dict[i]]
# 实现两个列表中的元素c和p逐一配对,并输出c+p
return cur
- 结果
方法二、递归
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if digits == '':
return []
dict = {'2': 'abc', '3': 'def',
'4': 'ghi','5': 'jkl', '6': 'mno',
'7': 'pqrs','8': 'tuv', '9': 'wxyz',
}
# 递归返回条件
if len(digits) == 1:
return [i for i in dict[digits[0]]]
#直接递归,digits的第一个元素组成列表m,digits的第二至end元素的映射组成列表n,然后m和n注意配对,输出m+n
return [m+n for m in dict[digits[0]] for n in self.letterCombinations(digits[1:])]
46. Permutations
方法一、递归(递归方法从最后的值开始插值;非递归方法则相反,由第一个数开始插值)
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if nums == []:
return []
if len(nums) == 1:
return [nums]
temp = []
for i in self.permute(nums[1:]):
for j in range(len(nums)):
cur = i[:] # 因为python的赋值实际上是赋值指针(浪费了我好多时间debug),所以要用切片复制出新的一个列表
cur.insert(j,nums[0])
temp.append(cur)
return temp
方法一改善:
class Solution(object):
def insert_num(self,m,n,z):
cur = m[:] #注意要切片复制出新列表
cur.insert(n,z)
return cur
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if nums == []:
return []
if len(nums) == 1:
return [nums]
# 运用了列表解析,与上一题类似
return [self.insert_num(m,n,nums[0]) for m in self.permute(nums[1:]) for n in range(len(nums))]
- 结果
方法二、借助现成模块
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
import itertools
return list(itertools.permutations(nums,len(nums)))