如何删除列表中具有特定词序的项

2024-04-29 15:10:48 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有名单

mylist = ["hello there", "Watermelons are delicious", "What is the color of my shirt"]
otherlist = ["1", "2", "3"]

我想检查“is the color of”是否是我列表索引中单词的顺序。如果是,我想从mylist和otherlist中删除该索引。你知道吗

更具体地说,我希望最终结果是:

otherlist = ["1", "2"]
mylist = ["hello there", "Watermelons are delicious"]

我在想:

while "is the color of" in mylist:
    del otherlist[mylist.index("is the color of")]
    del mylist[mylist.index("is the color of")]

但是,此代码不起作用。你知道吗


Tags: ofthehelloindexiswhatarecolor
3条回答
def find_and_remove(phrases, string_to_find):
    for index, phrase in enumerate(phrases):
        if string_to_find in phrase:
            phrases.pop(index)
            break

mylist = ["hello there", "Watermelons are delicious", "What is the colour of my shirt"]
find_and_remove(mylist, "is the colour of")
print mylist

这里有一种类似的方法来查找和删除string_to_find的第一个实例。你知道吗

如果您想要精确匹配,请使用单词边界检索地址:

import re

mylist = ["hello there", "Watermelons are delicious", "What is the colour of my shirt"]

mylist[:] = [s for s in mylist if not re.search(r"\bis the colour\b",s)])

输出:

['hello there', 'Watermelons are delicious']

mylist[:]意味着你改变了原来的列表,使用单词边界意味着is the colours等等。。不会匹配,这可能是或不是理想的行为。你知道吗

如果要获取包含子字符串的字符串的索引,请使用enumerate保留索引if re.search(r"\bis the colour\b",s)

print([ind for ind, s  in enumerate(mylist) if re.search(r"\bis the colour\b",s)])

输出:

[2]

如果您只想要第一个匹配,如果可能有多个:

ind = next((s for s in mylist f re.search(r"\bis the colour\b",s)),None)
if ind:
    print(ind)

如果要同时从两个列表中删除,请zip,检查子字符串是否匹配,如果匹配则删除:

 mylist = ["red is the color of my shirt", "hello there", "foo", "Watermelons are delicious",
          "What is the color of my shirt", "blue is the color of my shirt", "foobar"]
otherlist = ["0", "1", "2", "3", "4", "5", "6"]

for s1, s2 in zip(mylist, otherlist):
    if re.search(r"\bis the color\b", s1):
        mylist.remove(s1)
        otherlist.remove(s2)

print(mylist)

print(otherlist)

输出:

['hello there', 'foo', 'Watermelons are delicious', 'foobar']
['1', '2', '3', '6']

我猜您正在尝试查看字符串“是否是”列表中存在的任何字符串的一部分的颜色,以及是否要删除该列表元素。唯一的方法是在列表中循环(表示列表中的项),然后使用in关键字检查列表元素中正在搜索的子字符串。一个简单的方法是创建一个新列表,如果满足条件(即列表元素不包含您正在搜索的子字符串),则将列表元素复制到新列表中。但是,如果满足条件,您可以输入继续跳过它。你知道吗

编辑:如果您想根据与一个列表匹配的条件修改两个列表,您可以执行以下操作

mylist = ["hello there", "Watermelons are delicious", "What is the colour of my shirt"]
newlist = []
otherlist = ["1", "2", "3"]
for item in mylist:
  if "is the color of" in item:
    otherlist.pop(mylist.index(item));
    continue;
else:
 newlist.append(item)

相关问题 更多 >