1

I'd like to search and replace values in a list of of list. I've cobbled together answers to:

  1. Flatten a nested list
  2. Search for and replace a value
  3. Regroup the flat list into a list of lists

My current code works however I feel that it's more convoluted then it needs to be. Is there a more elegant way of doing this?

# Create test data- a list of lists which each contain 2 items
numbers = list(range(10))
list_of_lists = [numbers[i:i+2] for i in range(0, len(numbers), 2)]

# Flatten the list of lists
flat_list = [item for sublist in list_of_lists for item in sublist]
# Search for and replace values
modified_list = [-1 if e > 5 else e for e in flat_list]
# Regroup into a list of lists
regrouped_list_of_lists = [modified_list[i:i+2] for i in range(0, len(modified_list), 2)]
Community
  • 1
  • 1
Jason
  • 4,346
  • 10
  • 49
  • 75

2 Answers2

2

You're already using list comprehensions, just combine them:

replaced_list_of_lists = [
            [-1 if e > 5 else e for e in inner_list]
                for inner_list in list_of_lists
        ]
J Earls
  • 1,792
  • 8
  • 12
  • I'm not sure this is a good answer. List comprehension add already much to the readability, and combining them doesn't help much. – Antoine Sep 11 '16 at 23:37
  • Well this definitely removes some of the code so why not, but I personally try to avoid heavy use of list comprehension. – Antoine Sep 11 '16 at 23:40
  • @AntoineBolvy however, the original solution of flatting / replacing / recombing only works if you know exactly the format of the original list. If you want a general solution, you need either list comprehensions or nested for loops. – J Earls Sep 11 '16 at 23:42
  • Yeah of course, although it is useful to not forget that nested list comprehensions *are* nested for loops ;) – Antoine Sep 11 '16 at 23:54
2

Make the replacements in the sublists in a nested list comprehension without having to flatten and regroup:

numbers = list(range(10))
list_of_lists = [numbers[i:i+2] for i in range(0, len(numbers), 2)]
# here
list_of_lists = [[-1 if e > 5 else e for e in sublist] for sublist in list_of_lists]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139