-5

如何将此列表转换['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]

4

4 回答 4

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]
于 2013-02-17T14:27:38.503 回答
1

你也可以使用 string.maketrans 和 string.translate 来做类似的事情:

>>> import string
>>> t = string.maketrans("che", "012")
>>> test_str = "ccccchhhhheeeee"
>>> string.translate(test_str, t)
'000001111122222'
于 2013-02-17T14:40:42.537 回答
0

问题非常不清楚。假设您想对原始文件进行一些操作以获得输出,那么最好是 map。你可以传入任何你想要的函数,它会根据你的喜好以某种方式转换它

>>> 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]
于 2013-02-17T14:22:19.523 回答
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]
于 2013-02-17T14:30:02.513 回答