We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
对于简单的列表,比如[1, 2, 3],求和很简单,直接sum就可以了。
但是对于多维的,比如[[1, 2, 3], [4, 5, 6], [7], [8, 9]],该怎么求和呢?
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
这里铺平列表的方式就多了,我们看两个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随身听」和同名播客。如果对您有帮助,欢迎小额赞助👍。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
6.24-Python随身听-024-练习题-多维列表求和
对于简单的列表,比如[1, 2, 3],求和很简单,直接sum就可以了。
但是对于多维的,比如[[1, 2, 3], [4, 5, 6], [7], [8, 9]],该怎么求和呢?
方法1,递归操作,层层递进来处理
方法2,先铺平列表,然后直接求和
这里铺平列表的方式就多了,我们看两个itertools.chain和sum
最后在把列表直接sum一下就搞定了。
好了,这就是本期节目,感谢关注。
首发于公众号「Python随身听」和同名播客。如果对您有帮助,欢迎小额赞助👍。
The text was updated successfully, but these errors were encountered: