我的数组中充满了电子邮件地址,这些地址不断变化。例如
mailAddressList = ['chip@plastroltech.com','spammer@example.test','webdude@plastroltech.com','spammer@example.test','spammer@example.test','support@plastroltech.com']
如何在数组中找到同一字符串的多次出现并输出它是索引?
仅通过电子邮件和仅打印那些项目,其中索引列表大于1:
from collections import defaultdict
mailAddressList = ['chip@plastroltech.com',
'spammer@example.test',
'webdude@plastroltech.com',
'spammer@example.test',
'spammer@example.test',
'support@plastroltech.com'
]
index = defaultdict(list)
for i, email in enumerate(mailAddressList):
index[email].append(i)
print [(email, positions) for email, positions in index.items()
if len(positions) > 1]
# [('spammer@example.test', [1, 3, 4])]
尝试以下:
query = 'spammer@example.test''
indexes = [i for i, x in enumerate(mailAddressList) if x == query]
输出:
[1, 3, 4]
In [7]: import collections
In [8]: q=collections.Counter(mailAddressList).most_common()
In [9]: indexes = [i for i, x in enumerate(mailAddressList) if x == q[0][0]]
In [10]: indexes
Out[10]: [1, 3, 4]
注意:之前提交的解决方案比我的Pythonic更重要。但是在我的观点中,我之前写过的台词更容易理解。我只会创建一个字典,然后将邮件adresses添加为键,索引为值。
首先声明一个空词典。
>>> dct = {}
然后在 mailAddressList
中迭代邮件地址(m
)及其索引(i
),然后将它们添加到字典中。
>>> for i, m in enumerate(mailAddressList):
... if m not in dct.keys():
... dct[m]=[i]
... else:
... dct[m].append(i)
...
现在, dct
看起来像这个。
>>> dct
{'support@plastroltech.com': [5], 'webdude@plastroltech.com': [2],
'chip@plastroltech.com': [0], 'spammer@example.test': [1, 3, 4]}
有很多方法可以抓住[1,3,4]
。其中之一(也不那么Pythonic :))
>>> [i for i in dct.values() if len(i)>1][0]
[1, 3, 4]
或此
>>> [i for i in dct.items() if len(i[1])>1][0] #you can add [1] to get [1,3,4]
('spammer@example.test', [1, 3, 4])
这是一个字典理解解决方案:
result = { i: [ k[0] for k in list(enumerate(mailAddressList)) if k[1] == i ] for j, i in list(enumerate(mailAddressList)) }
# Gives you: {'webdude@plastroltech.com': [2], 'support@plastroltech.com': [5], 'spammer@example.test': [1, 3, 4], 'chip@plastroltech.com': [0]}
当然,它不是订购的,因为它是一张哈希表。如果要订购,则可以使用OrderedDict Collection。例如,像这样:
from collections import OrderedDict
final = OrderedDict(sorted(result.items(), key=lambda t: t[0]))
# Gives you: OrderedDict([('chip@plastroltech.com', [0]), ('spammer@example.test', [1, 3, 4]), ('support@plastroltech.com', [5]), ('webdude@plastroltech.com', [2])])
此讨论不太相关,但也可能对您有用。
mailAddressList = ["chip@plastroltech.com","spammer@example.test","webdude@plastroltech.com","spammer@example.test","spammer@example.test","support@plastroltech.com"]
print [index for index, address in enumerate(mailAddressList) if mailAddressList.count(address) > 1]
打印 [1, 3, 4]
,地址的索引在列表中不止一次发生。