当前位置: 动力学知识库 > 问答 > 编程问答 >

list - how to check if previous element is similar to next elemnt in python

问题描述:

I have a text file like:

abc

abc

abc

def

def

def

...

...

...

...

Now I would like o create a list

list1=['abc','abc','abc']

list2=['def','def','def']

....

....

....

I would like to know how to check if next element is similar to previous element in a python for loop.

网友答案:

You can create a list comprehension and check if the ith element is equal to the ith-1 element in your list.

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

This can be written within a for loop as well:

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

Check this post:

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', ....]

I think the best way to progress from here would be to use a dictionary

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

This will create a dictionary so the result would look like

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

This way you store all of the information you want. I proposed this solution because its rather messy to create an unknown number of lists to accommodate what you want to do, but it is easy and memory efficient to store the data in a dictionary from which you can create a list if need be. Furthermore, using dictionaries and sets allow you to have a single copy of each string (in this case).

If you absolutely need new lists let me know and I will try to help you figure it out

分享给朋友:
您可能感兴趣的文章:
随机阅读: