简体   繁体   English

编写此函数的正确方法是什么?

[英]What is the correct way to write this function?

I was making a program where first parameter is a list and second parameter is a list of dictionaries.我正在制作一个程序,其中第一个参数是一个列表,第二个参数是一个字典列表。 I want to return a list of lists like this:我想返回这样的列表列表:

As an example, if this were a function call:例如,如果这是一个函数调用:

make_lists(['Example'], 
           [{'Example': 'Made-up', 'Extra Keys' : 'Possible'}]
)

the expected return value would be:预期的回报值为:

[ ['Made-up'] ]

As an second example, if this were a function call:作为第二个例子,如果这是一个函数调用:

make_lists(['Hint', 'Num'],
           [{'Hint': 'Length 2 Not Required', 'Num' : 8675309},
            {'Num': 1, 'Hint' : 'Use 1st param order'}]
)

the expected return value would be:预期的回报值为:

[ ['Length 2 Not Required', 8675309],    
  ['Use 1st param order', 1] 
]

I have written a code for this but my code does not return a list of lists, it just returns a single list.我为此编写了一个代码,但我的代码不返回列表列表,它只返回一个列表。 Please can someone explain?请问有人可以解释一下吗?

def make_lists(s,lod):
  a = []
  lol =[]
  i = 0
  for x in lod:
      for y in x:
        for k in s:
          if(y==k):
            lol.append(x.get(y))
            i = i+1
  return lol

Expected Output:预期输出:

[ ['Length 2 Not Required', 8675309],['Use 1st param order', 1] ]

Output:输出:

['Length 2 Not Required', 8675309, 1, 'Use 1st param order']

Try this code - I've managed to modify your existing code slighty, and added explanation in the comments.试试这个代码 - 我已经设法稍微修改了你现有的代码,并在评论中添加了解释。 Essentially, you just need to use a sub-list and add that to the master list lol , and then in each loop iteration over elements in lod , append to the sub-list instead of the outermost list.本质上,您只需要使用一个子列表并将其添加到主列表lol ,然后在每次循环迭代lod元素时,附加到子列表而不是最外面的列表。

def make_lists(s,lod):
  a = []
  lol =[]
  i = 0
  for x in lod:
      ## Added
      # Here we want to create a new list, and add it as a sub-list
      # within 'lol'
      lols = []
      lol.append(lols)
      ## Done
      for y in x:
        for k in s:
          if(y==k):
            # Changed 'lol' to 'lols' here
            lols.append(x.get(y))
            i = i+1
  return lol


print(make_lists(['Example'], [{'Example': 'Made-up', 'Extra Keys' : 'Possible'}]))
print(make_lists(['Hint', 'Num'], [{'Hint': 'Length 2 Not Required', 'Num' : 8675309}, {'Num': 1, 'Hint' : 'Use 1st param order'}]))

Prints:印刷:

[['Made-up']]
[['Length 2 Not Required', 8675309], [1, 'Use 1st param order']]

A simpler solution更简单的解决方案

For a cleaner (and potentially more efficient approach), I'd suggest using builtins like map and using a list comprehension to tackle this problem:为了更干净(并且可能更有效的方法),我建议使用像map这样的内置函数并使用list理解来解决这个问题:

def make_lists(s, lod):
    return [[*map(dict_obj.get, s)] for dict_obj in lod]

But note, that this approach includes elements as None in cases where the desired keys in s are not present in the dictionary objects within the list lod .但请注意,如果列表lod中的字典对象中不存在s中所需的键,则此方法将元素包含为None

To work around that, you can pass the result of map to the filter builtin function so that None values (which represent missing keys in dictionaries) are then stripped out in the result:要解决这个问题,您可以将map的结果传递给filter内置函数,以便None值(代表字典中缺少的键)在结果中被去除:

def make_lists(s, lod):
    return [[*filter(None, map(dict_obj.get, s))] for dict_obj in lod]


print(make_lists(['Example'], [{'Extra Keys' : 'Possible'}]))
print(make_lists(['Hint', 'Num'], [{'Num' : 8675309}, {'Num': 1, 'Hint' : 'Use 1st param order'}]))

Output:输出:

[[]]
[[8675309], ['Use 1st param order', 1]]

The whole point of dictionaries, is that you can access them by key:字典的全部意义在于您可以通过键访问它们:

def make_lists(keys, dicts):
   result = []
   for d in dicts:
      vals = [d[k] for k in keys if k in d]
      if len(vals) > 0:
          result.append(vals)
   return result

Let's have a look what happens here:让我们来看看这里发生了什么:

We still have the result array, which accumulates the answers, but now it's called result instead of lol我们仍然有result数组,它累积了答案,但现在它被称为result而不是lol

Next we iterate through every dictionary:接下来我们遍历每个字典:

for d in dicts:

For each dictionary d , we create a list, which is a lookup in that dictionary for the keys in keys , if the key k is in the dictionary d :对于每个字典d ,我们创建一个列表,如果键k在字典d ,则在该字典中查找 keys 中的keys

vals = [d[k] for k in keys if k in d]

The specs don't detail this, but I assume if none of the keys are in the dictionary, you don't want it added to the array.规范没有详细说明这一点,但我假设如果字典中没有任何键,您不希望将其添加到数组中。 For that, we have a check if vals have any results, and only then we add it to the results:为此,我们检查vals是否有任何结果,然后才将其添加到结果中:

if len(vals) > 0:
    result.append(vals)

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

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