54. 螺旋矩阵(medium)

2019-05-30  本文已影响0人  genggejianyi

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

##code1
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return matrix
        res = []
        while matrix:
            res.extend(matrix.pop(0))
            matrix = list(zip(*matrix))[::-1]
        return res

#code2一行解决
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])

and如果都是真,返回最后一个值,如果有一个为假,则返回假;or返回第一个不是假的值。

有关例子:

[1,2,3] and [1]
Out[106]: [1]

[1] and [1,2,3]
Out[107]: [1, 2, 3]

[] and [1,2,3]
Out[108]: []

[] or [1]
Out[109]: [1]

[1] or [2] or []
Out[110]: [1]

[] or [] or [1]
Out[111]: [1]
a=[1,2,3]
b=(1,2,3)
c={1:"a",2:"b",3:"c"}
print(a,"====",*a)
print(b,"====",*b)
print(c,"====",*c)

运行结果为:
[1, 2, 3] ==== 1 2 3
(1, 2, 3) ==== 1 2 3
{1: 'a', 2: 'b', 3: 'c'} ==== 1 2 3
序列+*相当于解压,与zip的功能相反

其次有时在传入函数参数时有用,参数需要两个而你只有一个列表时,可以用*将列表拆成两个数独立传入函数:

def add(a, b):
    return a+b
data = [4,3]
print add(*data)
#equals to print add(4, 3)
上一篇 下一篇

猜你喜欢

热点阅读