加入两个连续的列表元素
我有一个列表名称
,看起来像这样,
names = ['Peter Orson', 'Marc Johnson', 'Peter', 'Johnson']
我想加入该列表的两个特定元素。
desired_names = ['Peter Orson', 'Marc Johnson', 'Peter Johnson']
警告:
- 我不能使用索引,
- 即使其他元素共享某些部分(例如相同的名字)
代码,我也只需要定位这两个单独的元素:
regex = re.compile(r'/^Peter$/)
for i in names:
if regex:
i = ' '.join(map(str, regex)) # join with next list element into one string
我认为我有正确的方法,但我不知道如何加入并替换匹配的字符串元素
i have a list names
that looks like this
names = ['Peter Orson', 'Marc Johnson', 'Peter', 'Johnson']
i want to join two specific elements of that list.
desired_names = ['Peter Orson', 'Marc Johnson', 'Peter Johnson']
caveat:
- i cannot use index
- i need to target only these two individual elements even though other elements share some parts (e.g. same first name)
code:
regex = re.compile(r'/^Peter$/)
for i in names:
if regex:
i = ' '.join(map(str, regex)) # join with next list element into one string
I think i have the right approach to my problem but i dont know how to join and replace the matched string elements
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如评论中所述,您不需要正则要这样做:
打印:
如果您不确定
是否在列表中
中,则可以之前检查:As stated in the comments, you don't need the regex to do that:
Prints:
If you aren't sure if
"Peter"
is in the list, you can check before: