sum()函数(Python内建)我们都用得不少,但她还有隐藏特技!您可知晓?👀
Python 官网:https://www.python.org/
Free:大咖免费“圣经”教程《 python 完全自学教程》,不仅仅是基础那么简单……
自学并不是什么神秘的东西,一个人一辈子自学的时间总是比在学校学习的时间长,没有老师的时候总是比有老师的时候多。
—— 华罗庚
本文质量分:
CSDN质量分查询入口:http://www.csdn.net/qc
Python内建函数sum(),大家再熟悉不过了吧,没少用她序列求和吧。😄明白易读,语句简洁。
Python 3.11.0 (main, Oct 29 2022, 21:50:32) [Clang 14.0.6 (https://android.googlesource.com/toolchain/llvm-project 4c603efb0 on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> sum((1, 2, 3, 4, 5, 6, 7, 8, 9))
45
>>> sum([1, 2, 3, 4, 5, 6, 7, 8, 9])
45
>>> sum({1, 2, 3, 4, 5, 6, 7, 8, 9})
45
>>> sum(range(10))
45
>>>
>>> c = dict.fromkeys((1, 2, 3, 4, 5, 6, 7, 8, 9))>>> c
{1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
>>> sum(c)
45
>>> a, b, c = 4, 5.6, 7.0
>>> sum((a, b, c))
16.6
>>>
我们一般用sum()对列表中的数值元素求和,殊不知她对元素是数值型对象的序列都可以求和。如元组、集合、字典的key以及变量序列。
但,您有没有想过,sum()还可以拉平二维数组,且可以对字符串为元素的列表操作,且不限二级序列长度,只要二级全是序列。
>>> nums = [[1, 2, 3], [4, 5, 6], [7, 8], [9]]
>>> sum(nums, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> d = [[1, 2, 3], [4, 5, 6], [7, 8], [9], ['f', 56]]
>>> sum(d, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 'f', 56]
>>>
>>> chars = [["I'm", ' ', 'a'], [' '], ['old' 'man', '.'], ['My name'], [' is '], ['dream', ' ', 'elf', '.']]
>>> sum(chars, [])
["I'm", ' ', 'a', ' ', 'old man', '.', 'My name', ' is ', 'dream', ' ', 'elf', '.']
>>> ''.join(sum(chars, []))
"I'm a old man.My name is dream elf."
>>>
惊奇不?迷茫不?
感到惊奇和迷豆对啰!因为我等凡人,根本想不到把sum()用于这样子的场景。👀直到我读到大师的代码,顿时惊呆——还有这样子的操控!!!
一顿惊诧过后,喜欢钻牛🐮角尖的我(我73的,属相牛🐂),开启了“寻根”历程……
>>> help(sum)
>>>
Help on built-in function sum in module builtins:
sum(iterable, /, start=0)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
(END)
sum(iterable, /, start=0)
此三条乃sum()的常规用法,其实她还有第四条——
就是您前面看到的炫酷玩法
正是这“连接列表”的第四条隐藏技能,可以换着花样玩儿花式——
>>> nums = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 13]
... ,[
...
...
... ]
... ,
... [14, 15, 16]]
>>> nums
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 13], [], [14, 15, 16]]
>>> sum(sum(nums, []))
124
>>> sum(range(17)) - 12
124
>>>
>>> nums = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]
... ]
>>>
>>> sum(sum(nums, []))
45
>>> sum(range(10))
45
>>>
>>> lis = [[''], ['城市', '新增本土', '无症状', ' 现有确诊', '高风险区'], ['重庆', '164', '7669', '2427', '3759'], ['北京', '1282', '3240', '6081', '3163'], ['广州广东', '1236', '6454', '20692', '974'], ['郑州河南', '130', '486', '3085', '1291'], ['']]
>>>print(','.join(sum(lis, [])))
,城市,新增本土,无症状,现有确诊,高风险区,重庆,164,7669,2427,3759,北京,1282,3240,6081,3163,广州广东,1236,6454,20692,974,郑州河南,130,486,3085,1291,
>>>
我的HOT博:
精品文章:
来源:老齐教室
◆ Python 入门指南【Python 3.6.3】
好文力荐:
全栈领域优质创作者——寒佬(还是国内某高校学生)博文“非技术文—关于英语和如何正确的提问”,“英语”和“会提问”是学习的两大利器。
CSDN实用技巧博文: