代码之家  ›  专栏  ›  技术社区  ›  cdub

基于某些真表达式在Python中简化列表和字典的循环

  •  0
  • cdub  · 技术社区  · 3 年前

    我试图纠正一种比一堆循环语句(如.Net中的LINQ或TypeScript:map=>{}中的lambda表达式)更简洁、简洁的方法,但不太确定如何或是否可能。

    我有两个这样的对象:

    # Input objects
    input_object.id = "Hello"
    # A list of integers
    input_object.values = [2,3,4,5,6]
    
    # Basic object my_object that has two properties
    my_object.name = "Hello"
    # The key in this dictionary are strings but are always valid numbers
    my_object.codes = {"1": "Howdy_There", "2": "Thank_You", "3": "Thank_you" }
    

    我可以这样做:

    saved_names = []
    
    if input.id ==  my_object.name
    
        #This will match for the above case
        # Now I want to go through all the my_object.codes and see if that key is in input_object.values
        # and if it is append the value to the save_names list
        
        # Something like below
        # This is my psuedo code attempt
        for c in my_object.codes
            if c (as an int) is in list input_object.values
                saved_names.append(add c's value)
    
    # Now make the saved_names list unique values only
    saved_names = (make saved names unique somehow)
    

    有没有一种方法可以简化这个过程,而不需要像某些内置函数那样的所有循环?

    1 回复  |  直到 3 年前
        1
  •  2
  •   OneCricketeer Gabriele Mariotti    3 年前

    saved_names = set(v for k, v in codes.items() if int(k) in values)
    

    也就是说

    code 字典,但只有键(作为int)位于 values 列表

    注意:字典键不需要是字符串