2017-10-17 41 views
0
import random 

avchars = ['a','b','c','d','e','f','g'] 
ra = random.randint(8,24) 
rb = random.randint(1,7) 
for i in range(ra): 
    file = open("pass","w") 
    ac = avchars(rb) 
    print(ac) 
    file.write(ac) 
file.close() 
print("Done") 

我想從上面的列表中生成8-24個字符。不過,我收到錯誤:當從列表生成時,不能調用列表對象

TypeError: 'list' object is not callable

+0

應該是'avchars [rb]',而不是'avchars(rb)'。 –

+1

返回'IndexError:列表索引超出範圍' – Finlay

+1

當然,你期望什麼?指數從'0'開始。所以'rb = random.randint(0,6)'。 –

回答

2

一個較短的版本:

with open('pass', 'w') as fobj: 
    fobj.write(''.join(random.choice('abcedfg') for _ in 
         range(random.randint(8, 24)))) 

的使用功能:

random.choice(seq) 

Choose a random element from a non-empty sequence.

random.randint(a, b) 

Return random integer in range [a, b], including both end points.

+0

謝謝你的工作<3。我十三atm和​​我的老師給了我一個考試超過4年,因爲他認爲我可以做到這一點(練習)。我根本不知道該怎麼做。這真的有幫助。謝謝 – Finlay

+0

非常有幫助。順便說一句,你可以[接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)一個答案,如果它解決了你的問題。 –

1

名單是不是一個元組或序列。因此,你不能使用:

avchars(rc) 

改用:

avchars[rc] 

那麼你的代碼將不會引發錯誤。