如何在python中一行打印列表?

2024-05-31 23:22:15 发布

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

如果我有这个代码,我需要打印在一行输出,我怎么能做到这一点?你知道吗

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') ]

Tags: andtheifonmatchsleeppresat
1条回答
网友
1楼 · 发布于 2024-05-31 23:22:15

您可以用列表替换整个函数

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')]

相关问题 更多 >