Is there a way to do a find and replace for lists that are sorted into groups?
Scenario:
my_list = [[1,5],[3,6],[-1,9]]
I want to replace all the values that are 1 or 3 to be replaced with 11 such that output is:
my_list = [[11,5],[11,6],[-1,9]]
I have been able to do the find replace by creating 3 variables and adding it such that it is one big list however I still want to retain the same form thus I am wondering how to do it while it's still in that form?
The alternative to the list comprehension solution would be modifying the original list with:
for group in my_list:
for i, x in enumerate(group):
if x in {1, 3}:
group[i] = 11
This would be the best option if your lists contain a large number of elements.
You could achieve this with a nested list comprehension such as:
my_list = [[y if y not in [1, 3] else 11 for y in x] for x in my_list]
This retains the nested list structure and replaces any 1 or 3 with 11. Output is:
[[11, 5], [11, 6], [-1, 9]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.