How to count all the items in the python list
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
print(len(board)) #prints 9 as the length of list
How do I print all the available items in the list (91) (without using any loop)
可以使用itertools.chain.from_iterable
将列表展平,然后正常计数和打印——
print(len(list(itertools.chain.from_iterable(board))))
You could use a reduction , eg:
import functools
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
length = functools.reduce(lambda total, item: total + len(item), board, 0)
print(length)
# 81
import functools
arr_len = functools.reduce(lambda a,b : len(a)+len(b),board))
sum(list(map(len,board)))
works as well
output:
81
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.