1. 程式人生 > >python中print中加個end引數的作用

python中print中加個end引數的作用

當我們在python裡列印一般用print來做,當我們想進行多次輸出並且連續輸出到同一行時,我們可以採用print後面的這個end引數填入空串來完成。比如在測試nlp的文字預測時,想連線輸出預測的一句話,但是每次預測一個單詞,就需要用到這個功能了。但是這個在python 3裡才有用。

程式碼片斷

 68         for iteration in range(self.num_iter):
 69             print('Iteration: %d'%iteration)
 70             model.fit(X, Y, batch_size=self.batch_size, epochs=self.num_epoch)
 71             # training 1 epoch, testing once
 72             test_idx = np.random.randint(len(self.input_chars))
 73             test_chars = self.input_chars[test_idx]
 74             print('test seed is: %s'%test_chars)
 75             print(test_chars, end='')
 76             for i in range(self.num_pred):
 77                 # test vectorized data
 78                 vec_test = np.zeros((1, self.seq_len, self.chars_count))
 79                 for i, ch in enumerate(test_chars):
 80                     vec_test[0, i, self.char2index[ch]] = 1
 81                 pred = model.predict(vec_test, verbose=0)[0]
 82                 pred_char = self.index2char[np.argmax(pred)]
 83                 print(pred_char, end='')
 84                 # continue to add new characters to generate new sequence
 85                 test_chars = test_chars[1:] + pred_char
 86             print('\n')

預測結果輸入如下:

Iteration: 23
Epoch 1/1
1739/1739 [==============================] - 0s 41us/step - loss: 1.6302
test seed is: eiving dat
eiving dat  fties in ue the seduor ef at inn es onets sher no oh toa titi init sac es oon ta aod soptha s duti