如果项目以特定顺序出现在列表中,我会尝试从列表中删除它们
我尝试过以下代码;
a = ["abc", "def", "ijk", "lmn", "opq", "rst", "xyz"]
b = ["ijk", "123", "456","123", "rst", "xyz" ]
counter=0
for i in b[:]:
print(i)
counter=counter+1
print(counter)
if i in a and i in a[counter+2]:
print(a)
print(">>>>>",a[counter+2])
b.remove(i)
print(b)
我正在寻找以下输出
b = ["ijk", "123", "456","123"]
从 b 中删除了 ["rst", "xyz"],因为它们在 a 中处于后 2 个后序列中。
最佳答案
这里有一种方法,即利用成对的查找来满足“序列”标准。
这个想法是预先构建“a”或“lookup_list”中所有对的集合。之后,使用对来迭代b
。如果找到一对,则设置一个标志以跳过两个元素(当前元素和下一个元素)。否则,附加第一个项目,因为可以保证它不会与顺序中的下一个项目一起出现。
演示:
from itertools import zip_longest
def remove_dupes_in_seq(lookup_list, b):
''' lookup_list: list from which you need to check for sequences
b: list from which you need to get the output that
has all elements of b that do not occur in a sequence in lookup_list.
'''
pair_set_lookup = set(zip(lookup_list, lookup_list[1:]))
#make a set of all pairs to check for sequences
result = []
skip_next_pair = False #boolean used to indicate that elements need to be skipped
for pair in zip_longest(b, b[1:]):
if skip_next_pair:
#set the boolean according to current pair, then perform a skip
skip_next_pair = pair in pair_set_lookup
continue
if pair in pair_set_lookup:
#pair found. set flag to skip next element
skip_next_pair = True
else:
#the first item is guaranteed to not occur in a sequence. Append it to output.
result.append(pair[0])
return result
a = ["abc", "def", "ijk", "lmn", "opq", "rst", "xyz"]
b = ["ijk", "123", "456","123", "rst", "xyz" ]
out = remove_dupes_in_seq(a, b) #['ijk', '123', '456', '123']
b2 = ["ijk","lmn","456","123","rst","xyz"]
out2 = remove_dupes_in_seq(a, b2) #['456', '123']
关于python - 如果重复的项目按特定顺序出现,则从列表中删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57482167/