如何使用python只打印一次输出?

2024-10-01 01:38:01 发布

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

列表中元组的大小是39

这是我的密码:

def joinphrase(joinph,i):
    length = len(joinph)
    res = ['%s %s' % (joinph[i][0], joinph[i + 1][0])
    for i in range(length)
       if i < length - 1 and joinph[i][2] == 'B-NP' and joinph[i + 1][2] == 'I-NP']
           return res 

def sentjoinphrase(joinph):
    return [joinphrase(joinph, i) for i in range(len(joinph))]


example = test_sents[0]
print (sentjoinphrase(example))

我想用一个条件连接来自不同元组的两个字符串,并打印连接输出。但是输出根据列表中元组的大小打印了39次

如何只打印一次输出


Tags: andin列表forlenreturndefnp
1条回答
网友
1楼 · 发布于 2024-10-01 01:38:01

您还有许多其他问题,但是对于print语句,看起来您正在创建一个包含

def sentjoinphrase(joinph):
       return [joinphrase(joinph, i) for i in range(len(joinph))]

这是初始短语的长度(for i in range(len(joinph)),然后在joinphrase函数中,用

for i in range(length) # Where length is equal to the length of joinph

因为这是一个列表理解,所以它只查看内部i变量,而不查看传递的参数。 这看起来像是调用joinphrase这个短语长度的倍数,在这里是39,因为传递的参数是不必要的。 因此,如果您只是从joinphrase中获得正确的值(只是多次),为什么不删除参数i如下所示:

def joinphrase(phrase):
    phrase_len = len(phrase)
    return ['%s %s' % (phrase[i][0], joinph[i + 1][0])
       for i in range(phrase_len)
       if i < phrase_len - 1 and phrase[i][2] == 'B-NP' and phrase[i + 1][2] == 'I-NP']

然后您就不再需要调用sentjoinphrase,因为参数是多余的,您可以直接调用joinphrase

相关问题 更多 >