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']