创新互联Python教程:Pythonextend()
python 中的extend()函数通过将给定 iterable 的所有元素添加到列表的末尾来帮助增加列表的长度。

站在用户的角度思考问题,与客户深入沟通,找到庆安网站设计与庆安网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站建设、做网站、企业官网、英文网站、手机端网站、网站推广、空间域名、雅安服务器托管、企业邮箱。业务覆盖庆安地区。
**list1.extend(iterable)** #where iterable may be list, tuple, string etc.
扩展()参数:
extend()函数接受一个参数。这个方法类似于append(),不同的是append()在列表的末尾添加了一个元素,但是在append()中我们可以添加多个元素。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 可重复的 | 可能是列表、元组、字符串等。 | 需要 |
扩展()返回值
这个方法不返回值。它通过添加元素来修改原始列表。
Python 中extend()方法的示例
示例 1:如何在 Python 中扩展works()方法
# flowers list
flowers = ['Rose', 'Lotus', 'Jasmine']
# another list of flowers
flowers1 = ['Sunflower', 'Dalia']
# appending flowers1 elements to flowers
flowers.extend(flowers1)
输出:
Flowers List : ['Rose', 'Lotus', 'Jasmine','Sunflower', 'Dalia']
示例 2:如何将元组和集合的元素添加到列表中?
# flowers list
flowers = ['Dalia']
# flowers tuple
flowers_tuple = ('Rose', 'Lotus')
# flowers set
flowers_set = {'Jasmine', 'Sunflower'}
# appending flowers_tuple elements to flowers
flowers.extend(flowers_tuple)
print('New flowers List:', flowers)
# appending flowers_set elements to flowers
flowers.extend(flowers_set)
print('Newer flowers List:', flowers)
输出:
New flowers List: ['Dalia', 'Rose', 'Lotus']
Newer flowers List: ['Dalia', 'Rose', 'Lotus', 'Sunflower', 'Jasmine']
示例 3:extend()& append()在 Python 中是如何工作的?
x1 = [1, 2]
x2 = [3, 4]
y = (5, 6)
# x1 = [1, 2, 5, 6]
x1.extend(y)
print(x1)
# x2 = [1, 2, (5, 6)]
x2.append(y)
print(x2)
输出:
[1, 2, 5, 6]
[1, 2, (5, 6)] 分享题目:创新互联Python教程:Pythonextend()
转载源于:http://www.jxjierui.cn/article/cccpgop.html


咨询
建站咨询
