I am just wondering if there is any better way of modifying the specific item in the list of list using List comprehension? In below example, I am squaring the second item of each list inside list, but, I don't want to eliminate inner list comprehension.
l = [
[1,2,3,],
[4,5,6,],
[7,8,9,],
]
nl = [[num**2 if i==1 else num for i, num in enumerate(x)] for x in l]
print nl
Not sure how to keep the inner comprehension but you could do something like this:
def square_idx_one(sl):
sl[1] **= 2
return sl
l = [
[1,2,3,],
[4,5,6,],
[7,8,9,],
]
nl = [square_idx_one(sl) for sl in l]
print (nl)
result:
[[1, 4, 3], [4, 25, 6], [7, 64, 9]]
But if you're modifying the original I think a for loop probably edges this solution for performance, not to mention memory
In your case, simply
print [[x, y**2, z] for x, y, z in l]
would do the job and says more explicitly what is going on. In general, do
from itertools import izip
p = (1, 2, 1) # element 0 power 1
# # element 1 power 2
# # element 2 power 1
# ...
print [[x**power for x, power in izip(row, p)] for row in l]
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.