【问题标题】:Implementing match condition with for and if loop in python在python中使用for和if循环实现匹配条件
【发布时间】:2019-04-29 09:52:19
【问题描述】:

我有一个如下的 json 数据,并且每个字段都有一个要匹配的 uri。 如果找到匹配项,则不要进行 [fields] 的下一次迭代。 概念是用户在搜索后点击了网址。 如果用户点击了第 3 个 url,则收集第 1、2、3 个数据值。不要追求第四个价值。

如果用户点击了第 5 个 url,则收集第 1 到第 5 个字段 uri 并退出该 json 对象。 取一个新的 json 对象并执行相同的过程。

[document]-> [fields1] -> [uri]
[document]-> [fields2] -> [uri]
[document]-> [fields3] -> [uri]
..... 
.. till 20-30 times. 

    I have written below code, but the above logic is not working. Kindly help on this. 



 uri='http://abcd.com/123.html'
    print(uri)
    for index_srch_log,row_srch_log in df_search_log_mongo.iterrows():
        RESPONSE = row_srch_log['RESPONSE']
        json_response = json.loads(RESPONSE)
        if 'documents' in json_response:
            field_data=json_response['documents']

            for row_resp_list in field_data:
                print('uri:',row_resp_list['fields']['uri'])
                match_found=False
                for i in row_resp_list['fields']['uri']:
                    print('i',i)

                    if uri == i:
                        print('yes matched')
                        match_found=True
                        break
                        print('found')
                    else:
                        print('not matched')
                        match_found=False
                    if match_found==True:
                        break

输出:

uri: ['http://abcddsc779072.html']
i value: http://abcddsc779072.html
not matched
uri: ['http://abcddsc932618.html']
i value: http://abcddsc932618.html
yes matched

-- 它应该停在这里并从 DF 获取下一个响应对象。 - 但它再次继续下一个 [fields] 数据。

  uri: ['http://abcddsc988555.html']
    i value:  http://abcddsc988555.html
    not matched
    uri: ['http://abcddsc1094909.html']
    i value: http://abcddsc1094909.html
    not matched

【问题讨论】:

标签: python json loops for-loop if-statement


【解决方案1】:

你没有打破外循环。考虑以下更改:

    if 'documents' in json_response:
        field_data=json_response['documents']

        for row_resp_list in field_data:
            print('uri:',row_resp_list['fields']['uri'])
            match_found=False
            for i in row_resp_list['fields']['uri']:
                print('i',i)

                if uri == i:
                    print('yes matched')
                    match_found=True
                    break
                else:
                    print('not matched')

            if match_found:
                break

【讨论】:

  • 非常感谢。你真棒。像魅力一样工作。
  • 哦,从来没有得到过这样的感激......)我的荣幸!
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 2012-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多