程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python foundation] several implementation methods of inserting multiple elements in the list

編輯:Python

List of articles

  • Method 1 :+ Number
  • Method 2 :insert function
  • Method 3 :append Method add
  • Method 4:extend()

Method 1 :+ Number

a = [1, 2, 3, 9, 10]
b = [4, 5, 6, 7, 8]
c = a[:3] + b + a[3:]
print(c)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Method 2 :insert function

fruit = ['pineapple','pear']
fruitlist = ['grape', 'uuu', 'ccc']
for x in fruitlist:
fruit.insert(len(fruit),x) # len(fruit) Express basis fruit Dynamic insertion of length of 
fruit

Method 3 :append Method add

fruit = ['pineapple','pear']
fruitlist = ['grape', 'uuu', 'ccc']
for x in fruitlist:
fruit.append(x)
fruit

Method 4:extend()

extend() Method add element ,extend() and append() The difference is that :extend() You don't think of lists or Yuanzu as a whole , Instead, they add the elements they contain to the list one by one .

l = ['Python', 'C++', 'Java']
# Additional elements 
l.extend('C')
print(l)
# Append tuple , Yuanzu was split into multiple elements 
t = ('JavaScript', 'C#', 'Go')
l.extend(t)
print(l)
# Add list , The list is also split into multiple elements 
l.extend(['Ruby', 'SQL'])
print(l)

[‘Python’, ‘C++’, ‘Java’, ‘C’]
[‘Python’, ‘C++’, ‘Java’, ‘C’, ‘JavaScript’, ‘C#’, ‘Go’]
[‘Python’, ‘C++’, ‘Java’, ‘C’, ‘JavaScript’, ‘C#’, ‘Go’, ‘Ruby’, ‘SQL’]


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved