【Python】【双语文献】列表元素替换(replace)方法实现

瞎扯

好久没更新了,一直在写项目/维护项目和写开发文档,今天且更新一篇笔记。

本文为技术文章,所以提供双语。
This article is about Information Technology, so I provide bilingual edition.

list().replace.jpg

正文/Body

话不多说,直接开门见山。

拦路虎/Problem

Python 编程语言使用者们,你们是否遇到过此问题:如何通过查找旧值来进行替换操作(即不知道索引,只知道旧值)?

Users of the Python programming language, have you ever encountered this problem: how to replace an old value by searching for it (that is, do not know the index, only know the old value)?

总所周知,在 Python 中,字符串(str)有一个便捷的方法:str().replace 。通过对字符串调用这个方法,可是实现在字符串内查找旧值并替换为新值并返回处理好的结果(不修改自身),甚至还可以指定替换个数。

As we known, in Python, there is a protable method in string (str) : str().replace. By calling this method on a string, it can achieve to find the old value and replace it into the new value then return the processed result (it never modify itself), even you can determine the number of times.

然而,list 类并没有提供相关方法。结合各种教程(大多是书),基本只能知道有以下方法:

However, there are not such a method. Combining various articles (Most of them are in books), we can basically only know the following methods

lst = []  # Here are many elements in the list
lst[x] = y  # x is index, y is the new value

这时没有索引(假如没有)的我们只能要么通过 .index(target) 的方法获取,然后再使用上面方法,但是这个方法只能返回第一个索引,后续的获取不了,如需获取还得使上正则模块,相当麻烦。

If we have no index, we can just get it by .index(target) , then use the solution above. But the returned content just included the first index (where the old value first appears) , no more. For get them, we even will use the re lib, that very troublesome.

启发/Inspire

偶然间发现一篇文章,介绍通过列表生成式直接替换所有的方法,发现这样做确实有效但是缺点意思,于是……

I stumbled upon an article that introduced the methods of directly replacing all the target through list generation. I found that this is really effective but it's not fun, so...

骚操作/My Approach

我写了一个继承 list 的类,在其基础上新增了一个 replace 方法,并且命名为 listPlus(属实有点不要脸).

I wrote a class that inherits list , added a replace method on its basis, and named it listPlus (I'm a bit shameless).

使用方法/Usage

导入/Import

直接复制代码或导入模块就可以了。

Copy the code or import the module directly is ok.

代码截图/Code Screenshot

image

注意:以上只是精简版!

Attention: This just a lite version!

若需文档和打印说明,请于文末获取完整版!

If you need the document and print messages, pls get full version at the end of this article.

调用说明/Call Description

以前我们定义一个列表一般使用以下方法:

Before, we usually define a variable of list by:

lst = []
lst = list()
lst = list([])

如果你需要使用到关于列表的替换方法,请你在需要的地方改用以下方式:

If you need use the replace method for a list, pls use this way instead of old way:

lst = listPlus()

但是注意:由于此类继承了 list ,所以其本质还是个列表,所以还是可以正常调用 list 类原有的 .remove 等方法。

Attention: Because the class inherited the list , so its essence is still a list. You can call the methods in list like .remove on it normally.

replace 方法/replace method

我们定义这样一个列表,它包含了各种类型的元素:

I define a list which includes many types of elements.

lst = listPlus([0, 1, 2, 3, None, True, False, print, "hello"])

现在,我只需要使用赋值的方式将 replace 返回的内容重新赋值给 lst,即可实现替换。

Now, I just need to reassign the content returned by replace to lst in the way of assignment to realize replacement.

lst = lst.replace(None, True)
lst = lst.replace("hello", "你好")
lst = lst.replace(0, 5)
lst = lst.replace(print, max)

# [5, 1, 2, 3, True, True, 5, <built-in function max>, '你好']

注意:为什么 replace 方法返回的是 listPlus 类型?答:如果返回列表,你还能再调用 replace 吗?

Attention: Why does the return type of replace is a listPlus? Answer: If it return a list, then you cann't called replace method.

另外,这个方法支持跨类型替换,如数字 -> 字符串。

In addition, this method supports cross-type substitution, such as number ->string.

最后,由于能力有限,像 __count (字符串类型中的按次数替换内容)的实现方法没做出来。

Finally, due to limited abilities, the implementation method of such as __count (replacing content by times in string type) has not been worked out.

Beta:replace_text

这个方法比较硬核,也易出错。原是其他教程里介绍的方法,但是实现过程之不严谨使其不能万能。

This method is more violent and prone to mistakes. It was originally the method introduced in other tutorials, but the implementation process is not rigorous enough to make it omnipotent.

实现方法:将列表转换为字符串后进行操作(此时调用的是 str().replace ),说到这,你应该知道本方法需传入参数:target 和 value 的类型了吧!没错,就是字符串。

Achievement: Convert the list into a string and then perform the operation (at this time, the call is' str(). replace '). Speaking of this, you should know that this method needs to incoming which type of parameters: target and value! Yes, it is a string.

警告:你最好确保你要替换的内容中不包括英文引号,如实在需要请成对使用,避免替换后的字符串转换失败!

Warning: You'd better ensure that the content you want to replace does not include English quotation marks. Please use them in pairs if necessary to avoid the string conversion failure after replacement!

使用示例/Example

lst = lst.replace_text('0', '5')

END

获取模块文件/Get the module file.

All of links used CN website. If you are not in CN and you can't visit them, pls use proxy or Virtual Private Network.

Gitee is a website similar to Github.

Source url
Online(Gitee, 【Recommended】) https://gitee.com/gkcoll/mydiys/blob/master/listPlus.py
网盘(夸克)/Netdisk(Quark) https://pan.quark.cn/s/3403de4c259e

阅读原文

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270