如何使用 python 字符串列表操作找到解决方案列表

How to find the solution list with python string list manipulation

我正在寻找一种方法来找到预期的输出: 这里我们有两个列表都包含字符串。请查看以下输入列表:

lst1 =["a: ","b: ","c:","d :"]
lst2 =[" b:"," a:","f:","g:","c: ","d:"]

预计:

outputlst=["a: ","b: ","c:","d :",f:","g:"] 

此处 outputlst 将始终包含 lst1 元素,而必须删除它们类似的 lst2 变体“a:”、“b:”、“c:”、“d:”。 到目前为止,我还没有得到列表迭代版本的结果。

如有任何想法,我们将不胜感激!

通常,我建议使用 outputlst = list(set(lst1 + lst2)),但由于两端的空格略有不同,您可以创建一个列表或集合(下面代码中的 already_contained)来检查是否删除尾随空格的字符串,并将其用作检查 lst2 中的字符串是否应传递给 outputlst

lst1 =["a: ","b: ","c:"]
lst2 =[" b:"," a:","f:","g:","c: "]
already_contained = set([c.replace(':', '').strip() for c in lst1])
outputlst = lst1 + [c for c in lst2 if c.replace(':', '').strip() not in already_contained]