在y

时间:2016-09-18 17:11:45

标签: python list python-3.x for-loop

我有这个脚本:

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的结构如下:

email1@email.com:test1
email2@email.com:test2
email3@gmail.com:test3

我如何添加到打印"尝试使用... bla bla"帐户的当前行?输出如:

Trying with: email1@email.com:test1 @1
Trying with: email2@email.com:test1 @2
Trying with: email3@email.com:test1 @3

2 个答案:

答案 0 :(得分:1)

您可以使用enumerate()和@JonClements建议的start参数:

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

答案 1 :(得分:0)

您正在寻找enumerate

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