简体   繁体   English

如何将嵌套列表的所有元素相乘

[英]How to multiply all elements of a nested list

I'm just starting out with Python and need some help. 我刚开始使用Python,需要一些帮助。 I have the following list of dictionaries that contain a list: 我有以下包含列表的词典列表:

>>> series
[{'data': [2, 4, 6, 8], 'name': 'abc'}, {'data': [5, 6, 7, 8], 'name': 'efg'}]
>>> 

How can I multiply each elements of inner lists by a constant without using loops and do it in place. 如何在不使用循环的情况下将内部列表的每个元素乘以一个常数,然后就位。

So if I have: 所以,如果我有:

>>> x = 100

The code should result in: 该代码应导致:

>>> series
[{'data': [200, 400, 600, 800], 'name': 'abc'}, {'data': [500, 600, 700, 800], 'name': 'efg'}]

The best I could come up with my limited knowledge is this (and I don't even know what "[:]" is): 我可以运用有限的知识得出的最好的结论是(而且我什至不知道“ [:]”是什么):

>>> for s in series:
...     s['data'][:] = [j*x for j in s['data']]
... 
>>> 

How can I remove the for loop? 如何删除for循环?

An explanation of the code or a pointer to docs would also be nice. 代码的解释或指向文档的指针也很好。

Thanks! 谢谢!

How can I remove the for loop? 如何删除for循环?

You can remove the loop with a combination of list and dict comprehensions: 您可以结合使用list和dict理解来删除循环:

>>> [{k:[j*100 for j in v] if k == 'data' else v for k,v in d.items()}
     for d in series]
[{'data': [200, 400, 600, 800], 'name': 'abc'}, {'data': [500, 600, 700, 800], 'name': 'efg'}]

However this less readable and no longer does the multiplication in-place. 但是,这种方法可读性较差,并且不再就地进行乘法运算。

So I think you shouldn't attempt to remove the loop. 因此,我认为您不应该尝试删除循环。 You should instead continue to do what you are already doing. 相反,您应该继续做您已经在做的事情。

An explanation of the code or a pointer to docs would also be nice. 代码的解释或指向文档的指针也很好。

I don't think it makes much sense to explain the above code, since we've already established that it isn't what you are looking for. 我认为解释上面的代码没有多大意义,因为我们已经确定它不是您想要的。 But perhaps you would like to know what the [:] does in your existing code. 但是也许您想知道[:]在现有代码中的作用。 For that, I refer you to this related question, that explains it in details: 为此,我请您参考此相关问题,以详细说明该问题:

You can remove the for loop in the list comprehension by using map : 您可以使用map删除列表理解中的for循环:

for s in series:
    s['data'] = map(lambda d: d*x, s['data'])

Mapping the multiplier by going through each element in the list: 通过遍历列表中的每个元素来映射乘数:

series = [{'data': [2, 4, 6, 8], 'name': 'abc'}, {'data': [5, 6, 7, 8], 'name': 'efg'}]
x=100

def mult_elements(series, x):
    for s in series:
        s['data']= map(lambda y:y*x, s['data'])
    return series

print mult_elements(series, x)

Doing it as a one liner with list comprehension: 以列表理解的方式做一个衬里:

series = [{'data': map(lambda y:y*x, s['data']), 'name':s['name']} for s in series]

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

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