Home > Enterprise >  How to index string using map function
How to index string using map function

Time:10-26

I have this list as an input but i want to give each alphabet an index for example k = 1 , i = 2 , s = 3 , s=3 ,a = 4

['k', 'i', 's', 's', 'a']

is there way to use map function effectively in this case

I have tried to use map function but it returns

<map object at 0x0000015513F6B4C0>

which is not readble even using list()

CodePudding user response:

from collections import defaultdict

l = ['k', 'i', 's', 's', 'a']

c = defaultdict(list)

for idx, el in enumerate(l):
    c[el].append(idx)

print(c) # defaultdict(<class 'list'>, {'k': [0], 'i': [1], 's': [2, 3], 'a': [4]})

You can now get all the indexes of a given element, e.g. c['s'] will return you a list of [2, 3]

CodePudding user response:

Here's an one liner to achieve this via using itertools.groupby along with enumerate as:

>>> from itertools import groupby
>>> my_list = ['k', 'i', 's', 's', 'a']

>>> {x[0]: i for i, x in enumerate(groupby(my_list), 1)}
{'k': 1, 'i': 2, 's': 3, 'a': 4}

However above approach is not optimal from performance point of view. Here's simpler implementation using a counter and an explicit for loop:

count = 1
my_dict = {}
my_list = ['k', 'i', 's', 's', 'a']

for x in my_list:
    if x not in my_dict:
        my_dict[x] = count
        count  = 1 

CodePudding user response:

you can use dictionary datatype in python which maps key and value.
a={'k':1, 'i':2, 's':3, 'a':4,}

CodePudding user response:

You can use a dictionary to store your custom index.

Here is a simple code example:

arr = ['k', 'i', 's', 's', 'a']

# dictionary format:
# { 'your_cumtom_index' : default_index(0, 1, 2,...) }
idx = {'myId-1': 0,
       'myId-2': 1,
       'myId-3': 2,
       'myId-4': 3,
       'myId-5': 4
       }

print(arr[idx['myId-2']])

CodePudding user response:

you can go with this approach solution-1

input

def myfunc(a, b):
  return (a,b)

a= ['k', 'i', 's', 's', 'a','w']
b = list(range(1,len(a) 1))

x = map(myfunc, a, b)
print(list(x))

output

[('k', 1), ('i', 2), ('s', 3), ('s', 4), ('a', 5), ('w', 6)]

NOTE:- if you go with a dictionary then the duplicate key not take for the index

i.e. - in your case in the list have two times (s) character you go with dictionary then (s) character indexed only one time

Solution - 2 with string

def myfunc(a, b):
  return (a,b)


p= 'kissa' 
b = list(range(1,len(list(p)) 1))

x = map(myfunc, list(p), b)
print(list(x)) # return list of tupel

Output - [('k', 1), ('i', 2), ('s', 3), ('s', 4), ('a', 5), ('n', 6)]
  • Related