Reshape the matrix: 给定一个二维矩阵,两个正整数r, c,将它reshape为r*c,如果不能reshape则返回原矩阵.
Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[1,2,3,4]] Explanation: The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
def matrixReshape(self, nums, r, c):
if r * c != len(nums) * len(nums[0]):
return nums
it = itertools.chain(*nums)
return [list(itertools.islice(it, c)) for _ in xrange(r)]
1、chain()
import itertools
A = ['a','b','c']
B = [1,2,3]
print(list(itertools.chain(A,B)))
output: ['a', 'b', 'c', 1, 2, 3]
2、compress()、islice()
import itertools
A = ['a','b','c','d','e','f','g']
B = [1,2,3]
#print(list(itertools.chain(A,B)))
C = [1,0,1]
print(list(itertools.compress(A,C)))
print(list(itertools.islice(A[::2],3)))
output:
['a', 'c']
['a', 'c', 'e']
3、dropwhile
import itertools
A = [1,5,6,4,6,1]
print(list(itertools.dropwhile(lambda x: x < 5, A)))
当条件不满足的时候开始。
takewhile()
import itertools
A = [1,5,6,4,6,1]
print(list(itertools.dropwhile(lambda x: x < 5, A)))
print(list(itertools.takewhile(lambda x: x < 6, A)))