[英]How to extract different indexes of the identical lists while reading a file using readlines in python
file = open(file = r'moto.txt')
bscAlertLines = file.readlines()
for alertLine in bscAlertLines:
if "MAINS_FAIL (1)" in alertLine:
inxAlert = bscAlertLines.index(alertLine)
print(inxAlert)
alertString = alertLine.split()
print(alertString)
Output looks like this:输出如下所示:
86
['EAS', '0', '0', '0', '17', 'FMIC', 'Untagged', '02-15-2020', 'MAINS_FAIL', '(1)']
194
['EAS', '0', '0', '0', '17', 'FMIC', 'Untagged', '03-24-2020', 'MAINS_FAIL', '(1)']
194
['EAS', '0', '0', '0', '17', 'FMIC', 'Untagged', '03-24-2020', 'MAINS_FAIL', '(1)']
243
['EAS', '0', '0', '0', '17', 'FMIC', 'Untagged', '03-22-2020', 'MAINS_FAIL', '(1)']
262
['EAS', '0', '0', '0', '17', 'FMIC', 'Untagged', '02-22-2020', 'MAINS_FAIL', '(1)']
194
['EAS', '0', '0', '0', '17', 'FMIC', 'Untagged', '03-24-2020', 'MAINS_FAIL', '(1)']
194
['EAS', '0', '0', '0', '17', 'FMIC', 'Untagged', '03-24-2020', 'MAINS_FAIL', '(1)']
194
['EAS', '0', '0', '0', '17', 'FMIC', 'Untagged', '03-24-2020', 'MAINS_FAIL', '(1)']
In this case, index 194 is repeated (as the content of lists is similar) but in the text file it is at different indexes like 285,322,400.在这种情况下,索引 194 重复(因为列表的内容相似),但在文本文件中它位于不同的索引处,如 285,322,400。 How can i retrieve these.我怎样才能检索这些。 How can i retrieve the original indexes as in file我如何检索文件中的原始索引
The index function will always return the first index the alertLine appears, and the enumerate function would do you a favor: index 函数将始终返回 alertLine 出现的第一个索引,而 enumerate 函数会对您有所帮助:
with open('moto.txt','r') as f:
for i,line in enumerate(f):
if "MAINS_FAIL (1)" in line:
print(i,line.split(),sep='\n')
In simple terms, the index() method finds the given element in a list and returns its position.简单来说, index() 方法在列表中找到给定的元素并返回其位置。
If the same element is present more than once, the method returns the index of the first occurrence of the element.如果同一元素出现多次,则该方法返回该元素第一次出现的索引。
code:代码:
file = open(file = r'moto.txt')
index = 0
bscAlertLines = file.readlines()
for alertLine in bscAlertLines:
index++
if "MAINS_FAIL (1)" in alertLine:
print(index-1)
alertString = alertLine.split()
print(alertString)
from collections import defaultdict
arr = [
["a", 15, "x"],
["b", 15, "x"],
["a", 15, "x"],
["a", 10, "y"],
["b", 15, "x"],
["b", 15, "y"],
["a", 10, "y"]
]
hash_map = defaultdict(list)
for i, list_el in enumerate(arr):
el = tuple(list_el)
hash_map[el].append(i)
print(hash_map)
This gives:这给出:
{
('a', 15, 'x'): [0, 2],
('b', 15, 'x'): [1, 4],
('a', 10, 'y'): [3, 6],
('b', 15, 'y'): [5]
}
Since lists are mutable and cannot be used as keys in dictionaries, I cast them to tuple's to be able to store it in a dictionary.由于列表是可变的并且不能用作字典中的键,我将它们转换为元组以便能够将其存储在字典中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.