Dj_ 96 :
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.
MARCO LAGALLA :
I propose here the simplest implementation, but not very efficient for large lists:
test = [(1, 'color: Red'), (2, 'color: Yellow'), (6, 'color: Pink'), (7, 'color: Blue'), (8, 'color: Green')]
max_index = max(test, key=lambda item:item[0])[0]
missing_values = []
for i in range(1, max_index + 1):
missing = False
for index, val in test:
if i != index:
missing = True
else:
missing = False
break
if missing:
missing_values.append((i,'color: None'))
new_test = test + missing_values
new_test_sorted = sorted(new_test, key=lambda x:x[0])
print(new_test_sorted)
That gives:
[(1, 'color: Red'), (2, 'color: Yellow'), (3, 'color: None'), (4, 'color: None'), (5, 'color: None'), (6, 'color: Pink'), (7, 'color: Blue'), (8, 'color: Green')]
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=360545&siteId=1