python变量和列表的用法整理

485次阅读
没有评论

python变量和列表的用法整理

python变量

在Python中使用变量时,不需要定义变量类型。使用方法可参考以下示例。

var_1 = 2021
var_2 = "Happy New Year!"
print("This is " + str(var_1))
print(var_2)

python列表

如果要修改列表中的某个元素,直接根据列表名称和元素对应的索引重新赋值;如果要在列表末尾添加元素,可以直接使用append()函数。如果要在列表中插入元素,需要使用insert()方法。如果要删除列表中的某个元素,如果知道该元素在列表中的位置,可以直接使用del语句。如果要删除列表末尾的元素,可以直接使用pop()方法。您也可以在pop()方法中输入元素的索引,以删除列表中任何位置的元素。以下示例显示了上述操作的具体用法。

cars = ['BMW', 'BENZ', 'Audi', 'Prosche']
print(cars)
cars[0] = 'BYD'
print("cars[0] = 'BYD'         ==> " + str(cars))
#Add element with append
cars.append('Volvo')
print("cars.append('Volvo')    ==> " + str(cars))
#Remove the last element with pop
cars.pop()
print("cars.pop()              ==> " + str(cars))
#Add an element with insert
cars.insert(0, 'Volvo')
print("cars.insert(0, 'Volvo') ==> " + str(cars))
#Remove an element with pop
cars.pop(0)
print("cars.pop(0)             ==> " + str(cars))
#Add element with append
cars.append('Volvo')
print("cars.append('Volvo')    ==> " + str(cars))
#Remove an element with del
del cars[3]
print("del cars[3]             ==> " + str(cars))

以上就是python变量和列表的用法整理,希望能对大家有所帮助!

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-06发表,共计1042字。
新手QQ群:570568346,欢迎进群讨论 Python51学习