简体   繁体   English

如何使用python中的列表理解来修改列表中的特定项目

[英]How to modify specific item in list of list using list comprehension in python

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 但是,如果您要修改原始文件,我认为for循环可能会降低该解决方案的性能,更不用说内存了

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]

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

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