列表中的元素索引

时间:2014-12-04 22:10:49

标签: python python-3.x

我需要处理电子邮件列表,剪切它们并使用迭代计数器输出

MailList = [email1@gmail.com, email2@gmail.com, email3@gmail.com] # I have a list with emails
# I need to process them and get next output: "User%number% is email1" I'm using something like:
for c in MailList:
    print('user'+ ' is '+c[0:7]) # what I need to insert here to get desirable counter for my output?

3 个答案:

答案 0 :(得分:1)

您需要使用@分割电子邮件:

>>> MailList = ['email1@gmail.com', 'email2@gmail.com', 'email3@gmail.com']
>>> for i in MailList :
...   print ('user'+ ' is {}'.format(i.split('@')[0]) )
... 
user is email1
user is email2
user is email3

答案 1 :(得分:0)

如果我理解正确,你想要这个:

MailList = ["email1@gmail.com", "email2@gmail.com", "email3@gmail.com"]

for index, value in enumerate(MailList):
    print('user {} is {}'.format(index, value.split("@")[0]))

有关enumerate的详细信息,请参阅the docs

答案 2 :(得分:0)

使用itertools.takewhile

>>> import itertools
>>> MailList = ['email1@gmail.com', 'email2@gmail.com', 'email3@gmail.com']
>>> for x in MailList:
...     print("user is {}".format("".join(itertools.takewhile(lambda x:x!='@',x))))
... 
user is email1
user is email2
user is email3

使用index

>>> for x in MailList:
...     print("user is {}".format(x[:x.index('@')]))
... 
user is email1
user is email2
user is email3

使用find

>>> for x in MailList:
...     print("user is {}".format(x[:x.find('@')]))
... 
user is email1
user is email2
user is email3