使用Python遍历SQL数据并与自身进行比较

2024-09-28 03:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我从sqlserver中提取数据,并使用Python重新格式化数据,并将其与NoSQL文档数据库中的数据进行比较。你知道吗

我从SQL返回的数据集如下所示: ('1','a') ('2','b') ('2','c') ('3','d') ('3','e') 第一个属性是ID,该ID可以重复多次,并附加第二个唯一标识符。 为了将SQL数据与NoSQL db中的JSON数据进行比较,我需要以以下格式放置数据:

{
'ID':2,
'IDInfo': 
    {'OtherID':'b'},
    {'OtherID':'c'}
}

我正在努力的是如何将一个列表与它本身进行比较。我必须比较第一行的ID和第二行的ID,然后第二行的ID和第三行的ID,以此类推。我知道如何在JavaScript中进行这种循环,但在Python中我无法理解。你知道吗

我尝试从索引0开始循环遍历列表,然后在索引1再次循环遍历同一列表并比较这些ID:

for index,row in enumerate(sqlResult):
    ID = row[0]
    i = index+1
    for index1,nextRow in enumerate(sqlResult, start=i):
        if (index1<i+1):
            nextRowId = nextRow[0]
        if (nextRowId == ID):
            #logic to append OtherID to a dynamically created object.
    print(ID,nextRowId) #Used this line to make sure the I was comparing the first ID to the next row's ID.

但是,这个逻辑只会循环/返回我的行列表中的第一行。在python中两次遍历同一对象并比较值的概念让我完全困惑。请帮忙。你知道吗


Tags: theto数据inid列表forsql
1条回答
网友
1楼 · 发布于 2024-09-28 03:21:29

简而言之,可以是这样的:

>>> sql = [('1', 'a'), ('2', 'b'), ('2', 'c'), ('3', 'd'), ('3', 'e')]
>>> json = {}
>>> for a,b in sql:
...  json[a] = [b] if a not in json else json[a]+[b] # Ternary Operator
>>> json
{'1': ['a'], '3': ['d', 'e'], '2': ['b', 'c']}
>>> json.items()
[('1', ['a']), ('3', ['d', 'e']), ('2', ['b', 'c'])]
>>> [{a:json[a]} for a in json] # List Comprehension
[{'1': ['a']}, {'3': ['d', 'e']}, {'2': ['b', 'c']}]
>>> formatted_json = [ {'ID':int(i),'IDInfo':[{'OtherID':v} for v in json[i]] } for i in json]  # Dictionary Comprehension in a List Comprehension
>>> import pprint
>>> pprint.pprint(formatted_json)
[{'ID': 1, 'IDInfo': [{'OtherID': 'a'}]},
 {'ID': 3, 'IDInfo': [{'OtherID': 'd'}, {'OtherID': 'e'}]},
 {'ID': 2, 'IDInfo': [{'OtherID': 'b'}, {'OtherID': 'c'}]}]

Python中还有一个用于标准编码/解码/格式化的“json”模块。希望有帮助!你知道吗

相关问题 更多 >

    热门问题