Home > other >  list elements replacing with specific values in python
list elements replacing with specific values in python

Time:03-27

I have a list list1=['a','b','c','a','c','d','a','b',10,20] , the list may contain some more elements with 'a','b','c','d' and 'e' in randomized position. I want to replace 'a' with 10, 'b' with 0, 'c' with 20, 'd' with 100, 'e' with -10. so basically the output list should be(for list1):[10,0,20,10,20,100,10,0,10,20]

I have a list list1=['a','b','c','a','c','d','a','b',10,20] , the list may contain some more elements with 'a','b','c','d' and 'e' in randomized index position. I want to replace 'a' with 10, 'b' with 0, 'c' with 20, 'd' with 100, 'e' with -10 in the list. so basically the output list should be(for list1):[10,0,20,10,20,100,10,0,10,20] note: I dont want to replace numerical elements

CodePudding user response:

What you want to do is a basic mapping of a value to another. This is usually done using a dictionary which defines the mapping and then iterate over all the values that you want to map and apply the mapping.

Here are to approaches which will get you the expected result. One is using a list comprehension, the second alternative way is using the map() built-in function.

list1 = ['a', 'b', 'c', 'a', 'c', 'd', 'a', 'b']

mapping = {
    "a": 10,
    "b": 0,
    "c": 20,
    "d": 100,
    "e": -10
}

# option 1 using a list comprehension
result = [mapping[item] for item in list1]
print(result)

# another option using the built-in map() 
alternative = list(map(lambda item: mapping[item], list1))
print(alternative)

Expected output:

[10, 0, 20, 10, 20, 100, 10, 0]
[10, 0, 20, 10, 20, 100, 10, 0]

Edit

As per request in the comments, here a version which only maps the values for which a mapping is defined. If no mapping is defined the original value is returned. Again I've implemented both variants.

# I have added some values which do not have a mapping defined
list1 = ['a', 'b', 'c', 'a', 'c', 'd', 'a', 'b', 'z', 4, 12, 213]

mapping = {
    "a": 10,
    "b": 0,
    "c": 20,
    "d": 100,
    "e": -10
}


def map_value(value):
    """
    Maps value to a defined mapped value or if no mapping is defined returns the original value
    :param value: value to be mapped
    :return:
    """
    if value in mapping:
        return mapping[value]
    return value


# option 1 using a list comprehension
result = [map_value(item) for item in list1]
print(result)

# another option using the built-in map()
alternative = list(map(map_value, list1))
print(alternative)

Expected output

[10, 0, 20, 10, 20, 100, 10, 0, 'z', 4, 12, 213]
[10, 0, 20, 10, 20, 100, 10, 0, 'z', 4, 12, 213]

As you can see 'z', 4, 12, 213 are not affected as for them there is no mapping defined.

  • Related