Python 2.7 如何查找列表元素

Python 2.7 如何查找列表元素,python-2.7,Python 2.7,我有这个清单 ['{"activities":[{"activity":"111","interface":"eds","clientIp":"12.207.212.130","logTime":1469811993000},{"activity":"121","dbCount":33,"totalHits":24,"query":"TI', 'the', 'plague","searchedFrom":"Unknown","searchType":"And","logTime":1469811

我有这个清单

['{"activities":[{"activity":"111","interface":"eds","clientIp":"12.207.212.130","logTime":1469811993000},{"activity":"121","dbCount":33,"totalHits":24,"query":"TI', 'the', 'plague","searchedFrom":"Unknown","searchType":"And","logTime":1469811994000}],"session":-2147479722,"customerId":"s8905647","groupId":"main","profileId":"eds"}']
只有当
“activity”:“121”
仅在出现
“activity”:“111”
之后才出现在该列表中时,我才想将整个列表按原样写入文件。像在这个例子中一样,第一个
“活动”:“111”
存在,之后的
“活动”:“121”
也存在,我希望这个列表被写入文件中,任何
“活动”:“121”
不在
“活动”:“111”
之后的任何地方,我不想写入


我该怎么做?请提供帮助。

我的解决方案基于这样一个假设,即您正在尝试搜索字典列表,因此我已更正了该列表。如果列表中的字典不包含要搜索的键,则也会出现错误。为此,我在函数中添加了简单的错误处理

我是一个Python新手,因此可能存在一个比我更优雅的解决方案,但它可能足以满足您的需要。它的工作原理如下:如果找到值为“111”的键“activity”的匹配项,则会在列表的其余部分搜索值为“121”的键“activity”的匹配项。很简单

如果您只考虑在活动111发生后在下一个字典中发现活动121的条件,则可以简单地将第14行更改为:

另外,我不确定您是在尝试编写字典,其中活动121是在活动111之后首先找到的,还是要编写整个字典列表。变量“myDictionaries”是整个列表,变量“i”只是在活动111之后找到活动121的第一个字典

您将从第16行开始写入,在我的解决方案中,该行只打印出列表,而不写入文件。因此,只需将其更改为您的文件写入解决方案。


我希望其他人能够帮助您解决后续问题,因为我没有足够的分数来使用评论功能。

作为另一个答案,我添加了一个解决方案,假设您的列表是一个带字符串的元素,在这种情况下,您最初发布的列表不需要更正。

#-*-编码:utf-8-*-
#您的示例列表
myListOfDicts=['{“活动”:[{“活动”:“111”,“接口”:“eds”,“客户端”:“12.207.212.130”,“日志时间”:146981193000},{“活动”:“121”,“数据库计数”:33,“总点击数”:24,“查询”:“TI”,“the”,“瘟疫”,“searchedFrom”:“未知”,“searchType”:“And”,“日志时间”:14698111994000}],“会话”:-2147479722,“客户ID”:“905647”,“groupId”:“main”,“活动”:“111}]
sanitizedList=str(myListOfDicts)。replace(“,”)#将列表转换为字符串并删除双引号以简化搜索
activityOne='activity:111',#设置字符串1的搜索模式
activityTwo='activity:121',#设置字符串2的搜索模式
foundFirst=False#初始化是否找到第一个字符串的状态
search111=sanitizedList.find(activityOne)#检查activity 111的位置
search121=sanitizedList.find(activityTwo)#检查活动121的位置
#如果找到活动111,则将foundFirst的状态设置为True
如果search111>0:
foundFirst=True
#如果在活动121之前找到活动111,则可以打印
如果先找到并搜索111
我很好奇您到底想做什么,因为您的问题的解决方案非常简单。我假设您正在动态创建列表,在这种情况下,您已经知道活动111是否添加到活动121之前,并且您可以基于此采取行动


无论如何,我希望这能有所帮助。

您的意思是,这个列表是一个包含字符串的单元素列表,看起来像一个字典吗?还是应该是一个字典列表?您可能只需要使用
json.loads()
在您的字符串上。这将返回一个更容易、更高效的字典。这是一个很好的解决方案,删除双引号非常好,将列表转换为字符串是我没有想到的事情,仍然是一个初学者。我基本上有一个包含350万行的文件,而您在myListOfDicts中添加的行只有1行在这些行中,我必须运行那个巨大的文件,只在活动121存在的地方获取行,然后是后续活动115/116,我可以从您的代码中找到线索..谢谢a tonI还有另一个难题要解决,现在我有200000行类似于这里的行:
if i[key] == valueTwo and foundOne and (dictCount - 1) == countHelp:
# -*- coding: utf-8 -*-
from __future__ import print_function # You can remove this line if you're using Python 3.

def searchDictionaries(key, valueOne, valueTwo, myDictionaries): # Define the function with four arguments
    dictCount = 0 # Initialize the count of dictionaries in the list
    foundOne = False # Initialize the state for meeting the first condition
    countHelp = 0 # This will help us determine if the second condition is met in the dictionary right after the first condition was met
    for i in myDictionaries: # Start looping through the list of dictionaries
        dictCount = dictCount + 1 # Increase count at every iteration
        try:
            if i[key] == valueOne: # Check if the first condition is met (if the value of activity is 111)
                foundOne = True # Change the state of meeting the first condition to True
                countHelp = dictCount # Keep this in case you want to modify the next line to only search in the next dictionary
            if i[key] == valueTwo and foundOne: # Check if the second condition (activity value of 121) is present in any subsequent dictionary
                # If you made it here, both conditions were met and you can write to file
                print(myDictionaries) # Write the whole list of dictionaries to file. Use print(i) if you want to just print the first dictionary where you found 121 after 111 was found.
                break # Stop searching
        except Exception as e: # Error handling
            print('Warning: %s - There is no key %s in dictionary %s.' % (e, e, dictCount))

    return

# Your example list of dictionaries
myListOfDicts = [
{'activity': '111', 'interface': 'eds', 'clientIp': '12.207.212.130', 'logTime': 1469811993000},
{'session': -2147479722, 'dbCount': 33, 'totalHits': 24, 'query': 'TI', 'the': 'plague', 'searchedFrom': 'Unknown', 'searchType': 'And', 'logTime': 1469811994000},
{'activity': '121', 'customerId': 's8905647', 'groupId': 'main', 'profileId': 'eds'}
]

# Now you can call the function searchDictionaries with your desired values > key, first value, second value, name of your list of dictionaries
searchDictionaries('activity', '111', '121', myListOfDicts)
# -*- coding: utf-8 -*-

# Your example list
myListOfDicts = ['{"activities":[{"activity":"111","interface":"eds","clientIp":"12.207.212.130","logTime":1469811993000},{"activity":"121","dbCount":33,"totalHits":24,"query":"TI', 'the', 'plague","searchedFrom":"Unknown","searchType":"And","logTime":1469811994000}],"session":-2147479722,"customerId":"s8905647","groupId":"main","activity":"111"}']

sanitizedList = str(myListOfDicts).replace('"', '') # Convert the list to string and emove double-quotes for simpler search

activityOne = 'activity:111,' # Set the search pattern for string 1
activityTwo = 'activity:121,' # Set the search pattern for string 2
foundFirst = False # Initialize status of whether the first string was found

search111 = sanitizedList.find(activityOne) # Check position of activity 111
search121 = sanitizedList.find(activityTwo) # Check position of activity 121

# Set status of foundFirst to True if activity 111 was found
if search111 > 0:
    foundFirst = True

# If activity 111 was found before activity 121, you can print
if foundFirst and search111 < search121:
    print 'Now you can write to file'