如何转换此列表['c','c','c','c','c','h','h','h','h','h','e','e','e','e','e']
这个[0,0,0,0,0,1,1,1,1,1,2,2,2,2,2]
答案 0 :(得分:2)
有点不清楚,这就是你要追求的吗?
In [2]: conv={'c':0,'h':1,'e':2}
In [3]: a=['c','c','c','c','c','h','h','h','h','h','e','e','e','e','e']
In [4]: [conv[i] for i in a]
Out[4]: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2]
答案 1 :(得分:1)
你也可以使用string.maketrans和string.translate来做类似的事情:
>>> import string
>>> t = string.maketrans("che", "012")
>>> test_str = "ccccchhhhheeeee"
>>> string.translate(test_str, t)
'000001111122222'
答案 2 :(得分:0)
问题非常明显。假设您想对原始操作进行一些操作以获得输出,那么就是地图。你可以传入你想要的任何功能,根据你的偏好以某种方式转换它
>>> a = ["a", "b", "c"]
>>> converted = map(lambda x: ord(x), a)
>>> print converted
[97, 98, 99]
基本思想是传递一个函数来映射,它将作用于原始列表中的每个元素并进行转换。例如,为了获得每个字母的字母值,我们可以将lambda函数写为lambda x : ord(char.lower()) - 96
例如:
>>> a = ["a", "b", "c"]
>>> converted = map(lambda x : ord(x.lower()) - 96 , a)
>>> print converted
[1, 2, 3]
答案 3 :(得分:0)
你的问题是非常缺乏的,但是如果我的猜测恰好降落,那么可能就像:
>>> s = ['c','c','c','c','c','h','h','h','h','h','e','e','e','e','e']
>>> from itertools import groupby, chain
>>> counted = enumerate(len(list(g)) for k,g in groupby(s))
>>> list(chain.from_iterable([i]*c for i,c in counted))
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2]
会给你你想要的吗?这使用groupby
来收集相邻的连续词:
>>> [(k, list(g)) for k,g in groupby(s)]
[('c', ['c', 'c', 'c', 'c', 'c']), ('h', ['h', 'h', 'h', 'h', 'h']), ('e', ['e', 'e', 'e', 'e', 'e'])]
>>> [len(list(g)) for k,g in groupby(s)]
[5, 5, 5]
和enumerate
计算它们:
>>> list(enumerate(len(list(g)) for k,g in groupby(s)))
[(0, 5), (1, 5), (2, 5)]
最后chain
以扁平形式重新组合它们:
>>> [[i]*c for i, c in enumerate(len(list(g)) for k,g in groupby(s))]
[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2]]
>>> list(chain.from_iterable([[i]*c for i, c in enumerate(len(list(g)) for k,g in groupby(s))]))
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2]