Python Map List of Strings to Integer List

后端 未结 9 1306
猫巷女王i
猫巷女王i 2020-12-31 23:05

Let\'s say I have a list

l = [\'michael\',\'michael\',\'alice\',\'carter\']

I want to map it to the following:

k = [1,1,2,3         


        
9条回答
  •  青春惊慌失措
    2020-12-31 23:27

    The function is zip

    E.g:

    >>> l = ['a','b','a','c']
    >>> k = [1,2,1,3]¨
    >>> zip(l,k)
    [('a', 1), ('b', 2), ('a', 1), ('c', 3)]
    

    If you want to use the items of l as index, you want an dictionary:

    >>> d = dict(zip(l,k))
    >>> d
    {'a': 1, 'c': 3, 'b': 2}
    >>> d['a']
    1
    >>> d['c']
    3
    >>> 
    

提交回复
热议问题