xera
xera

Reputation: 143

How to print the output only 1 time using python?

The size of the tuples in the list is 39.

Here is my codes:

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

I want to join two strings from the different tuples with a condition and print the join output. But the output printed 39 times according to the size of the tuples in the list.

How to print the output only 1 time?

Upvotes: 0

Views: 132

Answers (1)

Tui Popenoe
Tui Popenoe

Reputation: 2124

You have numerous other problems, but for your print statement, it looks like you are creating a list with

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

that is the length of your initial phrase (for i in range(len(joinph)) Then in your joinphrase function, you overwrite the value of the argument i with

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

Because this is a list comprehension, it looks at only the internal i variable, and not the passed argument. This looks like it is just calling joinphrase the number of times the length of the phrase, in this case 39, because the passed argument is unecessary. So if you are getting the correct value back just from joinphrase (just multiple times), why don't you remove the argument i like so:

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

Then you no longer need to call sentjoinphrase as the argument is superfluous, and you can just call joinphrase directly

Upvotes: 1

Related Questions