python循环遍历各列_如何在Python中循环遍历列?

环行列How do I loop through each column in the 2D array?# zip(*matrix) generates a transposed version of your matrix

for column in zip(*matrix):

do_something(column)

对你提出的问题/例子的回答I would want to do a method that checks if there's at least one column

in the 2D array that the column has the same values

一般方法:def check(matrix):

for column in zip(*matrix):

if column[1:] == column[:-1]:

return True

return False

一行:arr = [[2,0,3],[4,2,3],[1,0,3]]

any([x[1:] == x[:-1] for x in zip(*arr)])

说明:arr = [[2,0,3],[4,2,3],[1,0,3]]

# transpose the matrix

transposed = zip(*arr) # transposed = [(2, 4, 1), (0, 2, 0), (3, 3, 3)]

# x[1:] == x[:-1] is a trick.

# It checks if the subarrays {one of them by removing the first element (x[1:])

# and the other one by removing the last element (x[:-1])} are equals.

# They will be identical if all the elements are equal.

equals = [x[1:] == x[:-1] for x in transposed] # equals = [False, False, True]

# verify if at least one element of 'equals' is True

any(equals) # True

更新01

@BenC写道:"You could also skip the [] around the list comprehension so that any

just gets a generator that can be stopped early once/if it returns

false"

所以:arr = [[2,0,3],[4,2,3],[1,0,3]]

any(x[1:] == x[:-1] for x in zip(*arr))

更新02

您还可以使用集合(与@HelloV的答案合并)。

一行:arr = [[2,0,3],[4,2,3],[1,0,3]]

any(len(set(x))==1 for x in zip(*arr))

一般方法:def check(matrix):

for column in zip(*matrix):

if len(set(column)) == 1:

return True

return False

一个集合没有重复的元素,所以如果你将一个列表转换成一个集合set(x),任何重复的元素都会消失,所以,如果所有元素都相等,那么结果集合的长度等于一个len(set(x))==1。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值