Home python Python List List Generator

Python List List Generator

Author

Date

Category

I have a code that generates a list of lists

n = [[(i / j) for j in range (1,5)] for i in range ( 1.5)]

output

[[1.0, 0.5, 0.33333333333, 0.25],
[2.0, 1.0, 0.66666666666, 0.5],
[3.0, 1.5, 1.0, 0.75],
[4.0, 2.0, 1.33333333333, 1.0]]

Question 1) How to refer to the list of lists using the generator
2) How to organize this list of lists using the generator so that the values ​​are in the range from 0.5 to 2.5 remain unchanged, and the rest changed the sign on minus


Answer 1, Authority 100%

You created the source list using the generator. And it will not be possible to change anything with the generator by definition (logically, yes?). Therefore, you make another List Comprehension :

n = [[(i / j) for j in range (1,5)] for i in range ( 1.5)]
[[1.0, 0.5, 0.3333333333333333333333333333, 0.25]
 [2.0, 1.0, 0.6666666666666666, 0.5],
 [3.0, 1.5, 1.0, 0.75],
 [4.0, 2.0, 1.3333333333333333, 1.0]]
n = [[x if (x & gt; 0.5 and x & lt; 2.5) else x * -1 for x in y] for y in n]
[[1.0, -0.5, -0.3333333333333333, -0.25],
 [2.0, 1.0, 0.6666666666666666, -0.5],
 [-3.0, 1.5, 1.0, 0.75],
 [-4.0, 2.0, 1.3333333333333333, 1.0]]

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions