Skip to content Skip to sidebar Skip to footer

Reverse Itemgetter (itemsetter?): Inserting A List Of Items Into Specific Positions In A Larger List

I need to correct some values in a list. I am using itemgetter to extract the values into a smaller list. Afterwards I need to insert the items I corrected into the larger list. Is

Solution 1:

There's no itemsetter in the standard library, but it's easy to write:

defitemsetter(*items):
    iflen(items) == 1:
        item = items[0]
        defg(obj, value):
            obj[item] = value
    else:
        defg(obj, *values):
            for item, value inzip(items, values):
                obj[item] = value
    return g

Example:

lst = range(10, 20)
indexes = [1,3,5,7]

data = [81, 83, 85, 87]
setter = itemsetter(*indexes)

setter(lst, *data)
print lst # [10, 81, 12, 83, 14, 85, 16, 87, 18, 19]

Solution 2:

Yes, you can assign to a splice:

>>>big=[1,2,3,4]>>>small=[1.5, 1.7]>>>big[2:2]
[]
>>>big[2:2]=small>>>big
[1, 2, 1.5, 1.7, 3, 4]

and also if it's not empty:

>>>big=[1,2,3,4]>>>small=[1.5, 1.7]>>>big[2:3]=small>>>big
[1, 2, 1.5, 1.7, 4]

Solution 3:

for i, index in enumerate(indexes):
    line_as_list[index] = data[i]

This was simple. Sorry for asking.

Solution 4:

use splices

original = [1,2,3,4,5,6,7,8,9]

insert_element = ['foo']

insertion_index = 5

new_list = original[:insertion_index] + insert_element + original[insertion_index:]

print new_list

Post a Comment for "Reverse Itemgetter (itemsetter?): Inserting A List Of Items Into Specific Positions In A Larger List"