Skip to content

6.24-Python随身听-024-练习题-多维列表求和 #3

New issue

Have a question about this project? No Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “No Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? No Sign in to your account

Open
de8ug opened this issue Jun 24, 2020 · 0 comments
Open

6.24-Python随身听-024-练习题-多维列表求和 #3

de8ug opened this issue Jun 24, 2020 · 0 comments

Comments

@de8ug
Copy link
Contributor

de8ug commented Jun 24, 2020

6.24-Python随身听-024-练习题-多维列表求和

对于简单的列表,比如[1, 2, 3],求和很简单,直接sum就可以了。

但是对于多维的,比如[[1, 2, 3], [4, 5, 6], [7], [8, 9]],该怎么求和呢?

方法1,递归操作,层层递进来处理

def recursive_list_sum(data_list):
	total = 0
	for element in data_list:
		if type(element) == list:
			total = total + recursive_list_sum(element)
		else:
			total = total + element

	return total

方法2,先铺平列表,然后直接求和

这里铺平列表的方式就多了,我们看两个itertools.chain和sum

import itertools

list2d = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
# a = list(itertools.chain.from_iterable(list2d))  # call staticmethod from_iterable
a = list(itertools.chain(*list2d))   # init an object
b = sum(list2d, [])
print(a, b)

最后在把列表直接sum一下就搞定了。


好了,这就是本期节目,感谢关注。
首发于公众号「Python随身听」和同名播客。如果对您有帮助,欢迎小额赞助👍。

No Sign up for free to join this conversation on GitHub. Already have an account? No Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant