如何检查 Python 中的上一个元素是否与下一个元素相似



我有一个文本文件,如下所示:

abc
abc
abc 
def
def
def
...
...
...
...

现在我想创建一个列表

list1=['abc','abc','abc']
list2=['def','def','def']
....
....
....

我想知道如何检查下一个元素是否与python for loop中的前一个元素相似。

您可以创建列表推导式并检查第 i 个元素是否等于列表中的 ith-1 元素。

[ list1[i]==list1[i-1] for i in range(len(list1)) ] 
>>> list1=['abc','abc','abc']
>>> [ list1[i]==list1[i-1] for i in range(len(list1)) ]
[True, True, True]
>>> list1=['abc','abc','abd']
>>> [ list1[i]==list1[i-1] for i in range(len(list1)) ]
[False, True, False]

这也可以在 for 循环中编写:

aux_list = []
for i in range(len(list1)):
    aux_list.append(list1[i]==list1[i-1])

查看此帖子:

http://www.pythonforbeginners.com/lists/list-comprehensions-in-python/
for i in range(1,len(list)):
    if(list[i] == list[i-1]):
       #Over here list[i] is equal to the previous element i.e list[i-1]
file = open('workfile', 'r') # open the file 
splitStr = file.read().split() 
# will look like splitStr = ['abc', 'abc', 'abc', 'def', ....]

我认为从这里开始进步的最好方法是使用字典

words = {}
for eachStr in splitStr:
    if (words.has_key(eachStr)): # we have already found this word
        words[eachStr] = words.get(eachStr) + 1 # increment the count (key) value
    else: # we have not found this word yet
        words[eachStr] = 1 # initialize the new key-value set

这将创建一个字典,因此结果看起来像

print words.items()
[('abc', 3), ('def', 3)]

通过这种方式,您可以存储所需的所有信息。我提出了这个解决方案,因为创建未知数量的列表以适应您想要做的事情相当混乱,但是将数据存储在字典中既简单又内存高效,如果需要,您可以从中创建列表。此外,使用字典和集允许您拥有每个字符串的单个副本(在本例中(。

如果您绝对需要新列表,请告诉我,我会尽力帮助您弄清楚

最新更新