Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill the gaps in a list of tuples

I have a list of tuples like the following:

[(1, 'Red'), (2, 'Yellow'), (6, 'Pink'), (7, 'Blue'), (8, 'Green')]

The numbers in the tuple represent the index. However, since some of the indexes are missing in my input file, i need to insert some tuples in the list, and make the list look like the following:

[(1, 'Red'), (2, 'Yellow'), (3, None), (4, None), (5, None), (6, 'Pink'), (7, 'Blue'), (8, 'Green')]

If some of you have any ideas I would really appreciate if you take your time and comment something.

like image 635
Dj_ 96 Avatar asked Dec 14 '22 09:12

Dj_ 96


2 Answers

Here's a simple approach you can try out. If first gets the min and max number range, then gets the missing numbers using set difference set(A) - set(B), then concatenates the missing numbers with original list and sorts the result with sorted(). I've added comments to explain the approach as well :)

lst = [(1, 'Red'), (2, 'Yellow'), (6, 'Pink'), (7, 'Blue'), (8, 'Green')]

# Get only numbers
active_numbers = [x for x, _ in lst]

# Get min and max ranges
min_number, max_number = min(active_numbers), max(active_numbers)

# Get all possible numbers in range
all_numbers = set(range(min_number, max_number + 1))

# Find missing numbers using set difference set(A) - set(B)
difference = all_numbers - set(active_numbers)

# Add missing numbers and original numbers and sort result
result = list(sorted(lst + [(x, None) for x in difference]))

print(result)

Output:

[(1, 'Red'), (2, 'Yellow'), (3, None), (4, None), (5, None), (6, 'Pink'), (7, 'Blue'), (8, 'Green')]
like image 70
RoadRunner Avatar answered Dec 25 '22 13:12

RoadRunner


Assuming that either the list is sorted or that the result doesn't need to preserve the list order, you can use a dict created from the original list.

z = [(1, 'Red'), (2, 'Yellow'), (6, 'Pink'), (7, 'Blue'), (8, 'Green')]
d = dict(z)
low, high = min(d), max(d)
result = [(i, d.get(i)) for i in range(low, high + 1)]
like image 27
chepner Avatar answered Dec 25 '22 15:12

chepner