📅  最后修改于: 2020-09-20 13:35:30             🧑  作者: Mango
extend()
方法的语法为:
list1.extend(iterable)
在这里,所有iterable
元素都添加到list1
的末尾。
如前所述, extend()
方法采用可迭代方法,例如列表,元组, 字符串等。
extend()
方法修改原始列表。它不返回任何值。
# language list
language = ['French', 'English']
# another list of language
language1 = ['Spanish', 'Portuguese']
# appending language1 elements to language
language.extend(language1)
print('Language List:', language)
输出
Language List: ['French', 'English', 'Spanish', 'Portuguese']
# language list
language = ['French']
# language tuple
language_tuple = ('Spanish', 'Portuguese')
# language set
language_set = {'Chinese', 'Japanese'}
# appending language_tuple elements to language
language.extend(language_tuple)
print('New Language List:', language)
# appending language_set elements to language
language.extend(language_set)
print('Newer Language List:', language)
输出
New Language List: ['French', 'Spanish', 'Portuguese']
Newer Language List: ['French', 'Spanish', 'Portuguese', 'Japanese', 'Chinese']
您还可以使用以下命令将可迭代的所有元素附加到列表中:
1. + 运算符
a = [1, 2]
b = [3, 4]
a += b # a = a + b
# Output: [1, 2, 3, 4]
print('a =', a)
a = [1, 2, 3, 4]
2.列表切片语法
a = [1, 2]
b = [3, 4]
a[len(a):] = b
# Output: [1, 2, 3, 4]
print('a =', a)
a = [1, 2, 3, 4]
如果需要在列表末尾添加元素,则可以使用append()
方法。
a1 = [1, 2]
a2 = [1, 2]
b = (3, 4)
# a1 = [1, 2, 3, 4]
a1.extend(b)
print(a1)
# a2 = [1, 2, (3, 4)]
a2.append(b)
print(a2)
[1, 2, 3, 4]
[1, 2, (3, 4)]
要了解更多信息,请访问列表append()方法。