4

我有两个字符串变量 -string_Astring_B. string_A包含以下内容:

"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"

string_B包含:

"NANA" # "PAA" # "THREE" # "ELI"

我想删除其中的所有元素string_Astring_B打印后string_B它应该看起来像"NANA" # "PAA" # "ELI"

更新:

x = textA.split(' # ')
y = textB.split(' # ')

for i, j in enumerate(x):
if j in y[i]:
    pass
4

5 回答 5

7
a = '"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"'
b = '"NANA" # "PAA" # "THREE" # "ELI"'

a_elements = set(a.split(' # '))
b_elements = [key for key in b.split(' # ') if key not in a_elements]

b = ' # '.join(b_elements)
于 2013-08-15T11:31:49.243 回答
2

一个直接的解决方案:

a = '"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"'
b = '"NANA" # "PAA" # "THREE" # "ELI'

a_elements = [key.strip() for key in a.split('#')]
b_elements = [key.strip() for key in b.split('#')]
filtered_b_elements = [key for key in b_elements if key not in a_elements]
new_b = ' # '.join(filtered_b_elements)
于 2013-08-15T11:29:08.197 回答
1

你去:

' # '.join([x for x in string_B.split(' # ') if x not in string_A.split(' # ')])

如果您想要更好的性能,请先从 string_A 创建一个列表并将其用于“ not in”子句。

于 2013-08-15T11:32:58.300 回答
1

对于re粉丝:

import re

e = '"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"'
f = '"NANA" # "PAA" # "THREE" # "ELI"'

ea_pattern = re.compile(r'"([a-zA-Z]+)"')
ea = re.findall(ea_pattern,e)
fa = re.findall(ea_pattern,f)

answer = [x for x in fa if x not in ea]
print(answer)

list以任何你想要的方式使用它-

['NANA', 'PAA', 'ELI']

于 2013-08-15T11:52:22.510 回答
0
a = '"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"'
b = '"NANA" # "PAA" # "THREE" # "ELI"'
x = a.split(' # ')
y = b.split(' # ')

for j in x:
    if j in y:
        #HOW TO REMOVE
        y.remove(j)

xx = ' # '.join(x)
yy = ' # '.join(y)
print xx
print yy

以下输出:

'"ONE" # "TWO" # "THREE" # "FOUR" # "FIVE"'
'"NANA" # "PAA" # "ELI"'
于 2013-08-15T11:51:46.810 回答