Python:如何仅将一种类型的连续数字分组?

发布于 2025-02-03 05:25:07 字数 1744 浏览 1 评论 0原文

我编写了此程序,以在字符串中找到某些连续的重复数字并将其分组。该字符串仅包含0和1,我想通过将它们转换为数字来缩短重复的零。另外,为了避免混乱,我将所有1个转换为字母。例如:

item = list("00011101110100010111010001110000")

for i in item:
    if i == "1":
        item[item.index(i)] = "n"
    if i == "0":
        index = item.index(i)
        zeros = 0
        for shft, _ in enumerate(item):
            try:
                if item[index+shft] == "1":
                    break
                if item[index+shft] == "0":
                    item.pop(index+shft)
                    zeros+=1
            except IndexError:
                pass
        item.insert(index, zeros)
        
print(item)

我编写的该程序的预期输出是

[3, 'n', 'n', 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 4]

:我收到的输出是:

[2, 1, 'n', 'n', 'n', 1, 'n', 'n', 'n', 4, 'n', 1, 'n', 'n', 'n', 'n', 3, 'n', 1, 'n', 'n', 'n', 2, 1, 1]

我环顾四周可以分组连续字符,而我发现的最接近的东西是 this java示例,但是我在Python中实现它遇到了困难。

然后,我尝试了这种方法:

item = img[2]

zeros = 0
for idx, i in enumerate(item):
    if i == "0":
        zeros += 1
        item.pop(idx)
    elif i == "1":
        item[idx] = "n"
        if zeros != 0:
            item.insert(idx-1, zeros)
            zeros = 0
    elif i == "x":
        if zeros != 0:
            item.insert(idx-1, zeros)
            zeros = 0

print(item)

但是输出是:

['0', 2, '1', 'n', 'n', 1, '1', 'n', 'n', '1', '0', '1', 4, '1', 'n', 'n', '1', '0', 3, '1', 'n', 'n', '0', 2, '0', 'x']

任何人都可以告诉我一种比这更好,更快的方法,并告诉我我出了什么问题吗?

I wrote this program to find certain consecutive recurring digits in a string and group them. The string only contains 0 and 1, and I want to shorten the recurring zeros by converting them to a number. Also, to avoid confusion I converted all the 1s to a letter. For example:

item = list("00011101110100010111010001110000")

for i in item:
    if i == "1":
        item[item.index(i)] = "n"
    if i == "0":
        index = item.index(i)
        zeros = 0
        for shft, _ in enumerate(item):
            try:
                if item[index+shft] == "1":
                    break
                if item[index+shft] == "0":
                    item.pop(index+shft)
                    zeros+=1
            except IndexError:
                pass
        item.insert(index, zeros)
        
print(item)

The expected output for this program I wrote is

[3, 'n', 'n', 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 4]

But the output I get is:

[2, 1, 'n', 'n', 'n', 1, 'n', 'n', 'n', 4, 'n', 1, 'n', 'n', 'n', 'n', 3, 'n', 1, 'n', 'n', 'n', 2, 1, 1]

I looked around for something of this kind which can group consecutive characters, and the closest thing I found was this Java example but I was having trouble implementing it in python.

I then tried this approach:

item = img[2]

zeros = 0
for idx, i in enumerate(item):
    if i == "0":
        zeros += 1
        item.pop(idx)
    elif i == "1":
        item[idx] = "n"
        if zeros != 0:
            item.insert(idx-1, zeros)
            zeros = 0
    elif i == "x":
        if zeros != 0:
            item.insert(idx-1, zeros)
            zeros = 0

print(item)

But the output was:

['0', 2, '1', 'n', 'n', 1, '1', 'n', 'n', '1', '0', '1', 4, '1', 'n', 'n', '1', '0', 3, '1', 'n', 'n', '0', 2, '0', 'x']

Could anyone please show me a better and faster approach than this and show me where I'm going wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清欢 2025-02-10 05:25:07

您可以使用itertools.groupby将同一密钥的连续项目分组。由于在这种情况下,您实际上只想在离开1个单独的项目时分组0,我使用的技巧是使用一个键函数,该功能返回false 0 s for 0s和1s的增量数字,以便1S不会将他们的钥匙归为独特。您可以使用itertools.count来生成这样的增量数字:

from itertools import groupby, count

item = '00011101110100010111010001110000'

c = count(1)
print([
    'n' if k else sum(1 for _ in g)
    for k, g in groupby(item, lambda i: i == '1' and next(c))
])

此输出:

[3, 'n', 'n', 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 'n', 'n', 4]

You can use itertools.groupby for grouping consecutive items of the same key. Since you really only want to group 0s while leaving 1s separate items in this case, a trick I'd use is to use a key function that returns False for 0s and an incremental number for 1s so that 1s would not be grouped together as their keys are always unique. You can use itertools.count to generate such incremental numbers:

from itertools import groupby, count

item = '00011101110100010111010001110000'

c = count(1)
print([
    'n' if k else sum(1 for _ in g)
    for k, g in groupby(item, lambda i: i == '1' and next(c))
])

This outputs:

[3, 'n', 'n', 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 'n', 'n', 4]
星光不落少年眉 2025-02-10 05:25:07

您可以使用 itertools.groupbys.groupbys.groupby 使用嵌套的前循环,该循环决定是使用零的数量还是重复这些零的数量:

>>> import itertools as it
>>> item = '00011101110100010111010001110000'
>>> [x for k, g in it.groupby(item) for x in (('n' for _ in g) if k == '1' else [sum(1 for _ in g)])]
[3, 'n', 'n', 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 'n', 'n', 4]

You can use itertools.groupby with a nested for-loop which decides whether to use the number of zeros or to repeat the ones:

>>> import itertools as it
>>> item = '00011101110100010111010001110000'
>>> [x for k, g in it.groupby(item) for x in (('n' for _ in g) if k == '1' else [sum(1 for _ in g)])]
[3, 'n', 'n', 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 1, 'n', 'n', 'n', 1, 'n', 3, 'n', 'n', 'n', 4]
平安喜乐 2025-02-10 05:25:07

您为什么要在同一项目对象/变量中输出?

这是简单的方式 -

item = list("00011101110100010111010001110000")
output = []
count_zeros = 0 
for  i in item:
    if i == "1":
        if count_zeros != 0:
            output.append(count_zeros)
        output.append("n")
        # Set count of zero to 0
        count_zeros = 0
    elif i == "0":
        count_zeros = count_zeros + 1
    else:
        print("This characher is not handled {}".format(i))


 print(output)

why do you want to output in the same item object/variable?

It is simple way -

item = list("00011101110100010111010001110000")
output = []
count_zeros = 0 
for  i in item:
    if i == "1":
        if count_zeros != 0:
            output.append(count_zeros)
        output.append("n")
        # Set count of zero to 0
        count_zeros = 0
    elif i == "0":
        count_zeros = count_zeros + 1
    else:
        print("This characher is not handled {}".format(i))


 print(output)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文