简体   繁体   中英

How to multiply all elements of a nested list

I'm just starting out with Python and need some help. 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?

An explanation of the code or a pointer to docs would also be nice.

Thanks!

How can I remove the for loop?

You can remove the loop with a combination of list and dict comprehensions:

>>> [{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 :

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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