extend python_带有示例的Python列表extend()方法

短命女 2023-03-05 12:53 44阅读 0赞

extend python

列出extend()方法 (List extend() Method)

extend() method is used to extend a list, it extends the list by inserting the list of the elements at the end of the current list. The method is called with this list (current list, in which we have to add the elements) and another list (or any iterable) is supplied as an argument.

extend()方法用于扩展列表,它通过在当前列表的末尾插入元素列表来扩展列表。 用该列表(当前列表,我们必须在其中添加元素)调用该方法,并提供另一个列表(或任何可迭代)作为参数。

Syntax:

句法:

  1. list_name.index(iterable)

Parameter(s):

参数:

  • iterable – It represents a list of the elements or any iterable.

    可迭代 –表示元素列表或任何可迭代。

Return value:

返回值:

The return type of this method is , it returns nothing.

此方法的返回类型为 ,它什么也不返回。

Example 1:

范例1:

  1. # Python List extend() Method with Example
  2. # declaring the lists
  3. cars = ["Porsche", "Audi", "Lexus", "Audi"]
  4. more = ["Porsche", "BMW", "Lamborghini"]
  5. # printing the lists
  6. print("cars: ", cars)
  7. print("more: ", more)
  8. # extending the cars i.e. inserting
  9. # the elements of more list into the list cars
  10. cars.extend(more)
  11. # printing the list after extending
  12. print("cars: ", cars)

Output

输出量

  1. cars: ['Porsche', 'Audi', 'Lexus', 'Audi']
  2. more: ['Porsche', 'BMW', 'Lamborghini']
  3. cars: ['Porsche', 'Audi', 'Lexus', 'Audi', 'Porsche', 'BMW', 'Lamborghini']

Example 2:

范例2:

  1. # Python List extend() Method with Example
  2. # declaring the list
  3. x = [10, 20, 30]
  4. print("x: ", x)
  5. # inserting list elements and printing
  6. x.extend([40, 50, 60])
  7. print("x: ", x)
  8. # inserting set elements and printing
  9. x.extend({
  10. 70, 80, 90})
  11. print("x: ", x)

Output

输出量

  1. x: [10, 20, 30]
  2. x: [10, 20, 30, 40, 50, 60]
  3. x: [10, 20, 30, 40, 50, 60, 80, 90, 70]

翻译自: https://www.includehelp.com/python/list-extend-method-with-example.aspx

extend python

发表评论

表情:
评论列表 (有 0 条评论,44人围观)

还没有评论,来说两句吧...

相关阅读