Python数列中元素的修改
- 添加元素
– list.append()
— 无需定义数列长度
name = []
key = True
while key:
thing = input('Please enter a thing,press q to quit')
name.append(thing)
if thing == 'q':
key = False
print(name)
– list[i] = input(’ ')
—通过元素赋值来添加元素
bicycles = [0]*5
for i in range(5):
bicycles[i]=input('Please enter a thing,press q to quit')
print(bicycles)
但是以上两种都只能依次添加元素
– list.insert(position , ’ ’ )
— 在任何位置添加元素
name = ['chik','man','woman']
name.insert(0,'tachi')
name.insert(3,'car')
name.insert(5,'bike')
print(name)
>> ['tachi', 'chik', 'man', 'car', 'woman', 'bike']
>> 0. 1. 2. 3. 4. 5
- 删除元素
– del LIST[ position ]
— 删除任意指定位置的元素且以后不再用它**
name = ['sd','ad','lbj','kd']
print(name)
del name[0]
print(name)
>>['sd', 'ad', 'lbj', 'kd']
>>['ad', 'lbj', 'kd']
– LIST.pop( position )
— 删除元素之后还要获取被删除元素的数据
name = ['sd','ad','lbj','kd']
print(name)
pop_name = name.pop(1) #被删除元素保存在pop_name里
print(name)
print(pop_name)
>>['sd', 'ad', 'lbj', 'kd']
>>['sd', 'lbj', 'kd']
>>ad
– LIST.remove(content)
— 不知道删除的元素位于哪个位置, 若要删除的元素有相同的几个,那么每次只删除最前面那个
print(name)
name.remove('kd')
print(name)
>>['sd', 'ad', 'lbj', 'kd']
>>['sd', 'ad', 'lbj']
– 用remove和while结合删除所有相同的元素
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
while 'cat' in pets:
pets.remove('cat')
print(pets)
>> ['dog', 'dog', 'goldfish', 'rabbit']
本文介绍了Python中数列元素的修改方法,包括使用append()、insert()、del关键字、pop()和remove()函数进行添加和删除元素的操作。特别是强调了如何在特定位置插入元素,以及如何删除特定值或所有相同值的元素。
9368

被折叠的 条评论
为什么被折叠?



