2013-10-21 29 views
0

我一直在Python中製作座位表,在每個座位的位置顯示缺席。爲了列出缺席的例子,我決定使用randint生成0-15之間的隨機值,但是當我在矩陣中嘗試它時,它不起作用。然而,在矩陣外部使用的相同的線,只是印刷工作很好..我該如何解決這個問題?爲什麼randint不能在矩陣中工作,而是在其他地方工作? (Noob Python)

這裏是我的代碼:

import random 

student0Abs_EX = random.randint(0,15) 
student1Abs_EX = random.randint(0,15) 
student2Abs_EX = random.randint(0,15) 
student3Abs_EX = random.randint(0,15) 
student4Abs_EX = random.randint(0,15) 
student5Abs_EX = random.randint(0,15) 
student6Abs_EX = random.randint(0,15) 
student7Abs_EX = random.randint(0,15) 
student8Abs_EX = random.randint(0,15) 
student9Abs_EX = random.randint(0,15) 

print("\n\nExample Absences: \n") 
matrix = [[student0Abs_EX + '\t\t', student1Abs_EX + '\t\t', student2Abs_EX + '\t\t'], [student3Abs_EX + '\t\t', student4Abs_EX + '\t\t', student5Abs_EX + '\t\t'], [student6Abs_EX + '\t\t', 'Empty' + '\t\t', student7Abs_EX + '\t\t'], ['Empty' + '\t\t', student8Abs_EX+ '\t\t', student9Abs_EX + '\t\t']] 
for row in matrix: 
    print ' '.join(row) 

在此先感謝您的幫助!

+0

[有沒有必要把「解決」在你的標題。](http://meta.stackexchange.com/q/116101/175248)如果答案幫助你,接受它;如果你自己想出來,將它作爲答案發布,然後接受它。一個被接受的答案在某種程度上等於「解決」。 – Makoto

回答

2

random.randint函數沒有錯。問題在於,無論何時執行以下操作之一,您都試圖將intstr添加在一起:student0Abs_EX + '\t\t'

一個解決方法是改變所有那些str(student0Abs_EX) + '\t\t'

str功能整型轉換成對應的字符串。

+0

Ahhhh ..謝謝你,哈哈..我其實先嚐試過,但我只嘗試過一次,但仍然出現錯誤..我用str()標籤替換了所有的標籤,它工作,我感到很蠢,但是謝謝。 :) – ArnoldM904

0

因爲您不能只連接intstr

Type "help", "copyright", "credits" or "license" for more information. 
>>> 1 +'2' 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

看來你只需要一個隨機矩陣的文本表示。嘗試其他方式創建而不是[student0Abs_EX + '\t\t', student1Abs_EX + '\t\t', student2Abs_EX + '\t\t'], ...

相關問題