Python对lis中每个循环的特定int划分一个int列表

2024-09-30 16:27:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能更改这样的列表

[30,20,0,48,20,10,20,0,30]

收件人:

[[30,20],[48,20,10,20],[30]]

每次列表中有一个0时就除以它?我试过很多方法,但都占了太多的线(10行)。我已经看了很多关于堆栈溢出的列表拆分问题,我找不到任何有效的方法。你知道吗

编辑:

我在问有没有办法列表.拆分(0)或类似的东西,但答案似乎是没有办法做到这一点。我想知道我是否可以在一行中完成,或者是否有任何方法可以使用公共模块。我已经试过多行了,效果不错,但我觉得不方便。你知道吗

编辑2:

我试过的代码是:

list = [30,20,0,48,20,10,20,0,30]  #1, 1 list
newlist = []                       #2, 2 lists
addinglist = []                    #3, 3 lists
for x in list:                     #4
    if x == 0:                     #5
        newlist.append(addinglist) #6
        addinglist = []            #7
    else:                          #8
        addinglist.append(x)       #9 
newlist.append(addinglist)         #10
list = newlist                     #11 lines, 3 lists.
print(addinglist)

代码需要11行和3个列表(一个被修改,另外两个没有用)。你知道吗


Tags: 模块方法答案代码编辑列表堆栈lists
3条回答

正如TigerhawkT3所说:

Starting a result list, starting a running list, appending to the running list as long as a condition holds true, and appending the current list and starting a new one every time it doesn't is a very common task. Please demonstrate that you've tried something yourself first.

事实上,这是一项非常简单的任务,可以用4行Python代码来完成:

final=[]
for elem in [0]+x:
    if elem == 0: final.append([])
    else: final[-1].append(elem)

其中x是您的列表。你知道吗


这个答案的目的不是告诉你怎么做。但是告诉你,如果有任何相关的代码,你可以发布(不一定有效),这个答案会被更多人接受。你知道吗

总之:

  • 记住展示你的研究成果,只是说已经付出了努力并不重要,复制和粘贴你所发现/制作的东西并不是那么困难。你知道吗

I wanted to know if I can do it in one line or if there is any way I can use a common module.

是的,两个都是。您正在尝试对数据进行分组,以便groupby中的itertools是您的朋友:

from itertools import groupby

data = [30, 20, 0, 48, 20, 10, 20, 0, 30]

result = [list(group) for non_zero, group in groupby(data, lambda n: n != 0) if non_zero]

print(result)

输出

> python3 test.py
[[30, 20], [48, 20, 10, 20], [30]]
> 

我们使用一个键函数根据数据是否为零来捆绑数据。group变量包含bundle;non_zero变量(又名key)是一个布尔值,指示它是否是我们想要的bundle。你知道吗

这样做有效:

x=[10,20,30,0,4,5,6,0,1,1,1,1,1,1,0,1]

output=[]
temp=[]
for i in x:
    if i==0:
        output.append(temp)
        temp=[]
    else:
        temp.append(i)
output.append(temp)

其中,输出为:

[[10, 20, 30], [4, 5, 6], [1, 1, 1, 1, 1, 1], [1]]

代码很短,但我确信有更简洁的解决方案。你知道吗

相关问题 更多 >