I have my array is : Li = [[1,2,3],[4,5,6],[7,8,9]] how can check if value exist in an array . Example
if 5 exist in Li return Li[1][1] so I can change the value of that item by making Li[1][1]=
"X"
CodePudding user response:
If your nested list is always a 2D matrix of numbers, then you can find the indices fairly easily:
def find_indices(nested_list, value):
for i, inner_list in enumerate(nested_list):
for j, item in enumerate(inner_list):
if item == value:
return (i,j) # return a tuple containing the indices
Li = [[1,2,3],[4,5,6],[7,8,9]]
print(find_indices(Li, 5))
This example uses the enumerate function in Python, which gives you the index and item inside of an iterable object.
CodePudding user response:
To be honest it is hard to understand what u really want, or if u urself even know that. Here is some input that might help u:
from typing import List
def is_value_in_list_of_lists(
value_to_check: int, list_of_lists: List[List[int]]
) -> bool:
for v in list_of_lists: # v::List[int]
if value_to_check in v:
return True
return False
def replace_all_occurrences_of_value_in_list_of_lists(
value_to_check: int, value_to_replace_with: str, list_of_lists: List[List[int]]
) -> List[List[int]]:
if is_value_in_list_of_lists(value_to_check, list_of_lists):
modified_list_of_lists = []
for v in list_of_lists: # v::List[int]
if value_to_check not in v:
modified_list_of_lists.append(v)
else:
# modify list
v_modified = []
for val in v: # val::int
if val == value_to_check:
v_modified.append(value_to_replace_with)
else:
v_modified.append(val)
modified_list_of_lists.append(v_modified)
return modified_list_of_lists
else:
return list_of_lists
if __name__ == "__main__":
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# True
print(is_value_in_list_of_lists(5, lists))
# [[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
print(replace_all_occurrences_of_value_in_list_of_lists(5, "X", lists))
# oneliner
# [[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
print(list([*map(lambda x: "X" if x == 5 else x, y)] for y in lists))
