繁体   English   中英

搜索嵌套字典和元组列表和返回键

[英]Search Nested Dictionary and List of Tuple and Return Keys

需要帮助,这是我以前的一个后续问题,但有点过头了。 我有一个元组列表和一个字典(dct)。 对于 (s) 中的每个键,如果满足以下条件,我需要返回一个元组列表,其中包含 (dct) 中的匹配组键和 (s) 中的匹配键:

   Condition:
            All elements in at least 1 list within a specific group in (dct) is present in the string in (s). if True, return a list of tuples containing the associated group in (dct) and key in (s)


   s = [('[0]',
  'good morning i live in the city same day deliveries my wille at salmon today will be there today i have an easy ride'),
 ('[0, 1]',
  "christmas is upon us and my father is the greatest of all time and i will celebrate his greatness sad to hear she left"),
 ('[0]',
  'excited to be here i am a boy. thanks man my name is joe", "i live in a city'),
 ('[0]',
  'greetings, today is a good day i go to the village and learn i receive a scholarship')]
    
    dct = {
        "group1": [
            ["i am a boy", "my name is joe", "i live in a city"],
            ["my name is sam", "i go to school"],
        ],
        "group2": [
            ["i a stranger", "my present sister", "i love people"],
            ["my father is here"],
            ["i go to the village", "i receive a scholarship"],
        ],
        "group3": [
            [
                "i live in the city",
                "my wille at salmon today",
                "i have an easy ride",
            ],
            ["my father is the greatest", "sad to hear she left"],
            [
                "today is her birth day",
                "i will eat the rice",
                "tomorrow is her day",
            ],
        ],
    }

    Expected Results:

           [('[0]': 'group3'), ('[0, 1]': 'group3'), ('[0]': 'group1'), ('[0]': 'group2')]





My attempt:


   # function to return key for any value
   def get_key(val):
       for key, value in s.items():
           if val == value:
               return key
       return "key doesn't exist"

    out = []
    for k, v in dct.items():
        for lst in v:
            if all(item in s.get('[0,1]') for item in lst):
                out[k] = get_key(s.get('[0,1]'))
    
    print(out)
I figured out the a solution that works:

out_lst = []
for groupId, lst_lst in dct.items():
    for (Id, parag) in s:
        for lst in lst_lst:
            if all(item in parag for item in lst):
                if ((Id, groupId) not in out_lst):
                    out_lst.append((Id, groupId)) 
                
print(out_lst) 

               

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM