python如何替换list中指定的元素,实例代码 |
您所在的位置:网站首页 › list列表修改元素 › python如何替换list中指定的元素,实例代码 |
python如何替换list中指定的元素
Python中的list并没有内置类似字符串str中的replace()方法,可以用于替换指定的元素的值。python中要替换list中的元素值,一般可以通过索引的方式来对该索引位置上的元素进行重新赋值的方法来修改元素的值,语法如下: list[ index ] = newValue 但是,如果不清楚该指定的元素的索引该怎么办呢?可以通过list内置的方法index()来获取,应当注意的是,index()方法如果匹配不到指定的值,python会抛出ValueError,然后程序终止,不过这可以使用try...except来捕获ValueError并处理。 python替换list指定元素实例代码有了上面的思路,就可以来对替换list指定元素设计python程序了,并使用一个函数来对其进行封装: #-*- coding:utf-8 -*- def replace_list_element(ele,list1,new_ele): try: index = list1.index(ele) list1[index] = new_ele return list1 except ValueError as err: return str(ele) + ' is not in list' print(replace_list_element(1,[1,2,3],666)) print(replace_list_element(0,[1,2,3],3)) #终端或命令行工具输入命令运行文件,比如:python3 test.py,得到输出: [666, 2, 3] 0 is not in list |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |