【问题标题】:how to check if previous element is similar to next elemnt in python如何检查前一个元素是否与python中的下一个元素相似
【发布时间】:2014-08-09 05:26:10
【问题描述】:

我有一个文本文件,例如:

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

现在我想创建一个列表

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

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

【问题讨论】:

    标签: list python-2.7 for-loop


    【解决方案1】:

    您可以创建一个列表推导并检查第 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/
    

    【讨论】:

    • 这个答案需要解释你在做什么以及为什么。
    【解决方案2】:
    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]
    

    【讨论】:

    • 它仍然没有解释你在做什么以及为什么。
    【解决方案3】:
    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)]
    

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

    如果您绝对需要新列表,请告诉我,我会尽力帮助您解决问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-27
      • 2017-03-15
      • 2016-06-29
      • 1970-01-01
      • 2017-08-04
      • 2010-11-20
      • 2019-02-12
      • 1970-01-01
      相关资源
      最近更新 更多