如果我有这个代码,我需要在一行打印输出我怎么能这样做?
L = [('the', 'the'),('cat', 'cow'),('sat', 'sat'),('on', 'on'),('mat', 'mat'),('and', 'a'),('sleep', 'sleep')]
def getParaphrases(L):
pre_match = 0
mis_match = 0
after_match = 0
paraphrase = []
newpar = []
for x in L:
if x[0] == x[1]:
if not paraphrase == []:
print '\n Paraphrase:', paraphrase
paraphrase = []
pre_match += 1
mis_match = 0
else:
if pre_match >= 1:
if mis_match == 0:
paraphrase = []
paraphrase.append(x)
mis_match += 1
if after_match >= 1:
paraphrase.append(x)
after_match += 1
输出是:
Paraphrase: [('cat', 'cow')]
Paraphrase: [('and', 'a')]
但是,如何在一行中获得输出,例如,
Paraphrase [('cat', 'cow'), ('and', 'a') ]
答案 0 :(得分:1)
您可以使用列表推导替换整个函数
L = [('the', 'the'),('cat', 'cow'),('sat', 'sat'),('on', 'on'),('mat', 'mat'),('and', 'a'),('sleep', 'sleep')]
[(i,j) for i, j in L if i != j]
输出
[('cat', 'cow'), ('and', 'a')]