我怎样才能更改这样的列表
[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个列表(一个被修改,另外两个没有用)。你知道吗
正如TigerhawkT3所说:
事实上,这是一项非常简单的任务,可以用4行Python代码来完成:
其中
x
是您的列表。你知道吗这个答案的目的不是告诉你怎么做。但是告诉你,如果有任何相关的代码,你可以发布(不一定有效),这个答案会被更多人接受。你知道吗
总之:
是的,两个都是。您正在尝试对数据进行分组,以便
groupby
中的itertools
是您的朋友:输出
我们使用一个键函数根据数据是否为零来捆绑数据。
group
变量包含bundle;non_zero
变量(又名key
)是一个布尔值,指示它是否是我们想要的bundle。你知道吗这样做有效:
其中,输出为:
代码很短,但我确信有更简洁的解决方案。你知道吗
相关问题 更多 >
编程相关推荐