I am having a problem with list of lists. I want to know if there is a way to eliminate a column if some value is present Example:
List = [[1, 4, 1, 1, 1, 4, 1],
[2, 2, 2, 4, 2, 2, 2],
[3, 3, 3, 3, 3, 3, 3]]
if the number 4 is present in the list of lists eliminate that column giving for result:
Result_List = [[1, 0, 1, 0, 1, 0, 1],
[2, 0, 2, 0, 2, 0, 2],
[3, 0, 3, 0, 3, 0, 3]]
Due to 4 is present in List[0][1],List[1][3],List[0][5] Thanks for all the help.
CodePudding user response:
Try:
lst = [[1, 4, 1, 1, 1, 4, 1],
[2, 2, 2, 4, 2, 2, 2],
[3, 3, 3, 3, 3, 3, 3]]
out = list(
map(
list,
zip(
*(
[0] * len(lst) if any(v == 4 for v in c) else c
for c in zip(*lst)
)
),
)
)
print(out)
Prints:
[[1, 0, 1, 0, 1, 0, 1],
[2, 0, 2, 0, 2, 0, 2],
[3, 0, 3, 0, 3, 0, 3]]
CodePudding user response:
First transpose your list with zip
and *
so it becomes a list of columns:
>>> my_list = [[1, 4, 1, 1, 1, 4, 1],
... [2, 2, 2, 4, 2, 2, 2],
... [3, 3, 3, 3, 3, 3, 3]]
>>> [z for z in zip(*my_list)]
[(1, 2, 3), (4, 2, 3), (1, 2, 3), (1, 4, 3), (1, 2, 3), (4, 2, 3), (1, 2, 3)]
Then you can replace columns containing 4 with 0s:
>>> [[0 for _ in z] if 4 in z else z for z in zip(*my_list)]
[(1, 2, 3), [0, 0, 0], (1, 2, 3), [0, 0, 0], (1, 2, 3), [0, 0, 0], (1, 2, 3)]
and then transpose it back using the same zip(*(...))
trick:
>>> [list(z) for z in zip(*([0 for _ in z] if 4 in z else z for z in zip(*my_list)))]
[[1, 0, 1, 0, 1, 0, 1], [2, 0, 2, 0, 2, 0, 2], [3, 0, 3, 0, 3, 0, 3]]