如何在不创建子列表的情况下进行游程编码?
感谢您的帮助,我想知道如何创建一个对列表进行行程编码但不创建子列表的函数。原因是每个列表代表二维列表的一行。这样,当我去解码所有内容时,我将能够逐行进行解码,并保留原始列表的行。 如果可能,请修改我附上的代码,因为它通过写入重复值的编号而不是写入仅出现一次的值的编号来进行游程长度编码。
from itertools import groupby
def modified_encode(alist):
def ctr_ele(el):
if len(el)>1:
return [len(el), el[0]]
else:
return el[0]
return [ctr_ele(list(group)) for key, group in groupby(alist)]
我会解释一下。这是使用此处发布的函数的示例:
wall = 'wall'
concrete = 'concrete'
>>> map=[wall, wall, concrete, concrete]
>>> modified_encode(map)
[[2, 'wall'], [2, 'concrete']]
我想要的结果是这样的:
[2, 'wall', 2, 'concrete']
Thanking you for your help, I'd like to know how to make a function that does run-length encoding of a list, but doesn't create sublists. The reason is that each list represents a row of a two-dimensional list. In this way when I go to decode everything I will be able to do it line by line, having kept the lines of the original list.
If possible, modify the code that I enclose, as it does a run-length encoding by writing the numbers of the repeated values, not writing the numbers of the values that are present only once.
from itertools import groupby
def modified_encode(alist):
def ctr_ele(el):
if len(el)>1:
return [len(el), el[0]]
else:
return el[0]
return [ctr_ele(list(group)) for key, group in groupby(alist)]
I'll explain. Here is an example using the function posted here:
wall = 'wall'
concrete = 'concrete'
>>> map=[wall, wall, concrete, concrete]
>>> modified_encode(map)
[[2, 'wall'], [2, 'concrete']]
The result I would like instead is this:
[2, 'wall', 2, 'concrete']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您始终可以返回
list
- 即使对于单个项目[ el[0] ]
- 然后您可以使用可以添加列表的事实:[2,' wall'] + [2,'concrete'] + ['single']
给出[2,'wall',2,'concrete','single']
您甚至可以使用
总和(..., [])
为了这。结果:
编辑:
或者你可以用不同的方式编写它 - 没有
ctr_ele
- 并使用append()
You could always return
list
- even for single item[ el[0] ]
- and then you can use fact that you can add lists:[2,'wall'] + [2,'concrete'] + ['single']
gives[2,'wall',2,'concrete','single']
You may even use
sum(..., [])
for this.Result:
EDIT:
Or you could write it in different way - without
ctr_ele
- and useappend()