发布于 4年前

Python 3.5拼接列表的新语法

在Python 3.5之前的版本,拼接列表可以有这两种方法:

1、列表相加

list1 = [1,2,3]
list2 = [4,5,6]
result = list1 + list2

结果为一个新的列表

2、在原来列表上扩展

list1 = [1,2,3]
list2 = [4,5,6]
list1.extend(list2)

list1扩展后,结果为[1,2,3,4,5,6]

3、新语法

如果列表是由range()生成:

list1 = [1,2,3]
list2 = range(4,6)
result = list1+list2

那么列表直接相加会报错:

TypeError: can only concatenate list (not 'range') to list

新语法为Python3.5+

list1 = [1,2,3]
list2 = range(4,6)
result = [*list1,*list2]

这种语法称为Additional Unpacking Generalizations,在列表前加上星号*,表示解包列表。

©2020 edoou.com   京ICP备16001874号-3