编程语言
首页 > 编程语言> > 【Python3】列表字典集合元组

【Python3】列表字典集合元组

作者:互联网

1 列表

1.1 定义与索引

在Python中,第一个列表元素的下标为 0通过将索引指定为 -1

可以让Python返回最后一个列表元素

inventory = ['sword', 'armor', 'shield', 
            'big sword', 'big shiled'];
print(inventory[-1]);

1.2 修改 添加 删除

1.2.1 修改元素

inventory = ['sword', 'armor', 'shield', 
            'big sword', 'big shield'];
inventory[-1] = 'small shield'
print(inventory)
'''
运行结果:
['sword', 'armor', 'shield', 'big sword', 'small shield']
'''

1.2.2 添加元素

inventory1 = ['sword', 'armor', 'shield', 
            'big sword'];
inventory1.append('small shield');
print(inventory1)
#结果:['sword', 'armor', 'shield', 'big sword', 'small shield']
inventory2 = ['armor', 'shield', 
            'big sword', 'small shield'];
inventory2.insert(0, 'sword');
print(inventory2)
#结果:['sword', 'armor', 'shield', 'big sword', 'small shield']

1.2.3 删除元素

inventory = ['sword', 'armor', 'shield', 
            'big sword', 'big shield'];
del inventory[0];
print(inventory)
#结果:['armor', 'shield', 'big sword', 'small shield']
inventory = ['sword', 'armor', 'shield', 
            'big sword', 'big shield'];
popped_inventory = inventory.pop(4);
print(inventory)    #结果1
print(popped_inventory)        #结果2
#结果1:['sword', 'armor', 'shield', 'big sword']
#结果2:small shield
inventory = ['sword', 'sword', 'armor', 'shield', 
            'big sword', 'big shield'];
inventory.remove('sword');
print(inventory);
#结果:['sword', 'armor', 'shield', 'big sword', 'small shield']

标签:apple,shield,big,元组,fruit,sword,print,Python3,字典
来源: https://www.cnblogs.com/ohwell2aha/p/16492675.html