如何查找列表元素

时间:2016-08-05 16:36:08

标签: 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":1469811994000}],"session":-2147479722,"customerId":"s8905647","groupId":"main","profileId":"eds"}']

并且我只想在"activity":"121"出现"activity":"111"之后,只有"activity":"111"出现在文件中时才会将此整个列表写在文件中。就像在这个例子中一样,第一个"activity":"121"存在,后来"activity":"121"也存在,我希望这个列表写在文件和"activity":"111"之后private bool placeTower() { return tower == null; } //Method to check if where we want to place the tower is empty or not. public void OnMouseUp() { if (placeTower()) { prefabTower =GameObject.FindObjectOfType<TowerSelection().towerType; gold = GameManager.Manager.getGold(); if (gold > 0) { //ERRROR HEREEEEEEEEEEE ***tower = (GameObject)Instantiate( prefabTower , this.transform.position, this.transform.rotation);*** //Test code here GameManager.Manager.currentGold(-20); } else { Debug.Log("No hay suficiente dinero"); } } } 之后的任何列表void Start() {} void Update() { } public void TowerType (GameObject prefab) { towerType = prefab; } 1}},我不想写。

我该怎么做?请帮忙。

2 个答案:

答案 0 :(得分:0)

我的解决方案基于您尝试搜索字典列表的假设,因此我已经更正了列表。如果列表中的字典不包含您要搜索的密钥,您也会收到错误。为此,我已经为函数添加了简单的错误处理。

我是Python新手,因此可能存在比我更优雅的解决方案,但它可能足以满足您的需求。它的工作方式如下:如果发生了关键活动&#39;价值&#39; 111&#39;如果找到,则会搜索列表的其余部分以查找关键活动&#39;使用&#39;值121&#39;。很简单。

但是,如果在活动111发生后,如果在下一个字典中找到活动121,则只考虑满足条件,您只需将第14行更改为:

if i[key] == valueTwo and foundOne and (dictCount - 1) == countHelp:

此外,我不确定您是否正在尝试编写活动111之后首先找到活动121的字典,或者您是否要编写整个字典列表。变量&#39; myDictionaries&#39;是整个列表,变量&#39; i&#39;是活动111之后发现活动121的第一本字典。

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

# -*- 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)

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

答案 1 :(得分:0)

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

# -*- 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'

我很好奇你正在尝试做什么,因为你的问题的解决方案非常简单。我假设您正在动态创建列表,在这种情况下,您已经知道在活动121之前是否添加了活动111,您可以基于此采取行动。

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