题目
这个题挺难的,首先得解决一个问题.把原来的数组拉平.
就像
flat = sum(nums, [])
或者使用itertools.chain()
如:
import itertools
a= ['a','aa','aaa']
b= itertools.chain(a)
c= itertools.chain(*a)
print(a)
print(list(b))
print(list(c))
[‘a’, ‘aa’, ‘aaa’]
[‘a’, ‘aa’, ‘aaa’]
[‘a’, ‘a’, ‘a’, ‘a’, ‘a’, ‘a’]
或者这样,
def flatten(l):
for el in l:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
l = [1, 2, [3, 4, [5, 6]], ["abc", "def"]]
l2 = [x for x in flatten(l)]
print l2
或者,
items = [y for x in nums for y in x]
代码
class Solution(object):
def matrixReshape(self, nums, r, c):
import itertools
flat=list(itertools.chain(*nums))
new=[]
if r*c==len(nums)*len(nums[0]):
for k in range(r):
new.append(flat[k*c:(k+1)*c])
return new
return nums
方案1: numpy 方法:(简单易懂)
import numpy as np
class Solution(object):
def matrixReshape(self, nums, r, c):
try:
return np.reshape(nums, (r, c)).tolist()
except:
return nums
方案2: Oneliner
def matrixReshape(self, nums, r, c):
return nums if len(sum(nums, [])) != r * c else map(list, zip(*([iter(sum(nums, []))]*c)))
可读性更高的版本:
def matrixReshape(self, nums, r, c):
flat = sum(nums, [])
if len(flat) != r * c:
return nums
tuples = zip(*([iter(flat)] * c))
return map(list, tuples)
其中,map函数:
def f(x):
return x*x
print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
方案3:
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)]
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if len(nums[0])*len(nums) != r*c:
return nums
else:
items = [y for x in nums for y in x]
return [items[x*c : ((x+1)*c)] for x in range(r)]