Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

python - Modify nested list elements using list comprehension

I wanted to produce lst_new such that,

items = (.1, .5, .9)
lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

lst_new == [[[.1, 2, 3], [.4, 5, 6], [.7, 8, 9]], [[.5, 2, 3], [2, 5, 6], [3.5, 8, 9]], [[.9, 2, 3], [3.6, 5, 6], [6.3, 8, 9]]]

Using list comprehension,

lst_new = [x[0] * i for i in items for x in lst]

But obviously it doesn't work as intended. Help?

question from:https://stackoverflow.com/questions/65930733/modify-nested-list-elements-using-list-comprehension

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is that you're only including the first value of x, not all of them, and you need a nested list comprehension to add depth to the list structure:

lst_new = [[[x[0] * m] + x[1:] for x in lst] for m in items]

Output

[
 [[0.1, 2, 3], [0.4, 5, 6], [0.7, 8, 9]],
 [[0.5, 2, 3], [2.0, 5, 6], [3.5, 8, 9]],
 [[0.9, 2, 3], [3.6, 5, 6], [6.3, 8, 9]]
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...