2016-09-18 24 views
-1

我有這樣的腳本:打印項目的當前數量在一個週期內對於x y中

accounts = open("accounts.txt").readlines() 

y = [x.strip().split(":") for x in accounts] 

for account in y: 
    print ("Trying with: %s:%s" % (account[0], account[1])) 

文件accounts.txt是structred這樣的:

[email protected]:test1 
[email protected]:test2 
[email protected]:test3 

我如何才能增加打印「試用... bla bla」帳戶的當前行嗎?等的輸出:

Trying with: [email protected]:test1 @1 
Trying with: [email protected]:test1 @2 
Trying with: [email protected]:test1 @3 
+1

[在Python訪問索引 '的' 循環]的可能的複製(http://stackoverflow.com/questions/522563/accessing-the- python-for-loops) –

回答

1

您可以使用enumerate(),與start參數通過@JonClements的建議:

for i, account in enumerate(y, start=1): 
    print ("Trying with: %s:%s @%d" % (account[0], account[1], i)) 

您還可以使用拆包,使線條更加可讀:

for i, (mail, name) in enumerate(y, start=1): 
    print ("Trying with: %s:%s @%d" % (mail, name, i)) 

最後,正如@idjaw通知它,有a better way to format string這是推薦的舊風格:

for i, (mail, name) in enumerate(y, start=1): 
    print("Trying with: {}:{} @{}".format(mail, name, i)) 
+0

但是,我會直接在這裏使用字符串格式,只需要:'「嘗試:{}:{} @ {}」。format(account [0],account [1] ,i)' – idjaw

+0

你可以跳過'i + 1'作爲'enumerate'開始的參數:'enumerate(y,start = 1)'對於你正在使用'i'來說更加明確。 –

+0

另外 - Python 3中沒有引入新風格的字符串格式 - 自Python 2.6 –

0

您正在尋找enumerate

for position, account in enumerate(y): 
    print ("Trying with: %s:%s @%d" % (account[0], account[1], position)) 
+0

謝謝!它已經工作了! – CatchJoul

相關問題