列表降维
,例子如下:oldlist = [[1, 2, 3], [4, 5]]
# 想得到结果:
newlist = [1, 2, 3, 4, 5]
# 方法一,粗暴拼接法:
newlist = oldlist[0] + oldlist[1]
# 方法二,列表推导式:
newlist = [i for j in range(len(oldlist)) for i in oldlist[j]]
for i in oldlist[j]
则会遍历取出 j 子列表的元素,由于 j 取值的区间正对应于原列表的全部索引值,所以,最终达到解题目的。# 方法三,巧用sum:
newlist = sum(oldlist,[])
sum(iterable[, start])
,sum() 函数的第一个参数是可迭代对象,如列表、元组或集合等,第二个参数是起始值,默认为 0 。其用途是以 start 值为基础,再与可迭代对象的所有元素相“加”。The iterable’s items are normally numbers, and the start value is not allowed to be a string.
For some use cases, there are good alternatives to
sum()
. The preferred, fast way to concatenate a sequence of strings is by calling''.join(sequence)
. To add floating point values with extended precision, seemath.fsum()
. To concatenate a series of iterables, consider usingitertools.chain()
.
TypeError: sum() can’t sum strings [use ”.join(seq) instead]
math.fsum()
;当要拼接一系列的可迭代对象时,应考虑使用 itertools.chain()
。itertools.chain()
可以将不同类型的可迭代对象串联成一个更大的迭代器,这在旧文《Python进阶:设计模式之迭代器模式》中也有论及。