如何检查前一个元素是否与python中的下一个元素类似

时间:2014-08-09 05:26:11

标签: list python-2.7 for-loop

我有一个文本文件,如:

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

现在我想创建一个列表

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

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

3 个答案:

答案 0 :(得分:2)

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

[ 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/

答案 1 :(得分:1)

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]

答案 2 :(得分:0)

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

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

如果你绝对需要新的名单,请告诉我,我会尽力帮你解决问题