加入两个连续的列表元素

发布于 2025-01-24 08:38:13 字数 559 浏览 0 评论 0原文

我有一个列表名称,看起来像这样,

names = ['Peter Orson', 'Marc Johnson', 'Peter', 'Johnson']

我想加入该列表的两个特定元素

desired_names = ['Peter Orson', 'Marc Johnson', 'Peter Johnson']

警告:

  1. 我不能使用索引,
  2. 即使其他元素共享某些部分(例如相同的名字)

代码,我也只需要定位这两个单独的元素:

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:

  1. i cannot use index
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奢欲 2025-01-31 08:38:13

如评论中所述,您不需要正则要这样做:

names = [
    "Peter Orson",
    "Marc Johnson",
    "Peter",
    "Johnson",
]

idx = names.index("Peter")
names[idx] = names.pop(idx) + " " + names[idx]
print(names)

打印:

['Peter Orson', 'Marc Johnson', 'Peter Johnson']

如果您不确定是否在列表中中,则可以之前检查:

if "Peter" in names:
    idx = names.index("Peter")
    names[idx] = names.pop(idx) + " " + names[idx]

As stated in the comments, you don't need the regex to do that:

names = [
    "Peter Orson",
    "Marc Johnson",
    "Peter",
    "Johnson",
]

idx = names.index("Peter")
names[idx] = names.pop(idx) + " " + names[idx]
print(names)

Prints:

['Peter Orson', 'Marc Johnson', 'Peter Johnson']

If you aren't sure if "Peter" is in the list, you can check before:

if "Peter" in names:
    idx = names.index("Peter")
    names[idx] = names.pop(idx) + " " + names[idx]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文