基于python中重复值的组阵列值

发布于 2025-02-10 08:23:33 字数 469 浏览 1 评论 0原文

其值如下,

size=[9, 41, 1368, 887, 307, 9, 114, 81, 9, 34, 12, 13, 12, 4, 548, 3, 77] 

以保持恒定值= 9

我创建了一个数组

b=41
c=1368,887,307

需要对这些值进行分组,

b=114
c=81

b=34
c=12,13,12,4,548,3,77

for i in range(0,len(size)):    
    if size[i-1]!=9:
        if(size[0]-size[i])!=0:
            print(size[i])
    

I have created an array whose values are as follows

size=[9, 41, 1368, 887, 307, 9, 114, 81, 9, 34, 12, 13, 12, 4, 548, 3, 77] 

I need to group these values keeping a constant value = 9.

Example output required

Group 1

b=41
c=1368,887,307

Group 2

b=114
c=81

Group 3

b=34
c=12,13,12,4,548,3,77

I have no clue how to achieve this, i have tried out following code.

for i in range(0,len(size)):    
    if size[i-1]!=9:
        if(size[0]-size[i])!=0:
            print(size[i])
    

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

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

发布评论

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

评论(1

你怎么敢 2025-02-17 08:23:33

您必须为这些9值扫描输入,并且每次遇到它时,都会启动一个新列表以收集其他值。

一旦拥有那些符合人物,您就可以迭代这些并在bc部分报告:

size = [9, 41, 1368, 887, 307, 9, 114, 81, 9, 34, 
        12, 13, 12, 4, 548, 3, 77] 
# Spread data into sub lists, separated by 9-values
result = [[]]
for val in size:
    if val == 9:
        result.append([])  # Start a new sub list
    else:
        result[-1].append(val)  # Append to last sub list
# Remove empty sublists
result = [lst for lst in result if lst]
# Output in terms of b and c:
for b, *c in result:
    print("b=", b)
    print("c=", c)

You'll have to scan the input for those 9 values, and each time you encounter it, start a new list for gathering the other values.

Once you have those sublists, you can iterate those and report on the b and c parts of those:

size = [9, 41, 1368, 887, 307, 9, 114, 81, 9, 34, 
        12, 13, 12, 4, 548, 3, 77] 
# Spread data into sub lists, separated by 9-values
result = [[]]
for val in size:
    if val == 9:
        result.append([])  # Start a new sub list
    else:
        result[-1].append(val)  # Append to last sub list
# Remove empty sublists
result = [lst for lst in result if lst]
# Output in terms of b and c:
for b, *c in result:
    print("b=", b)
    print("c=", c)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文