7

Python 列表踢出某个元素上机作业题

 2 years ago
source link: https://www.v2ex.com/t/821251
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Python

Python 列表踢出某个元素上机作业题

  going · 6 小时 58 分钟前 · 909 次点击

请根据输入的原始列表,输出目标列表:

原始列表:[1,2,None,None,None,None,None,None,3,4,5,6,None,None,None,None,7,8,9,10]

目标列表: [1,2] [3,4,5,6] [7,8,9,10]

12 条回复    2021-12-10 15:43:42 +08:00

princelai

princelai      6 小时 30 分钟前   ❤️ 1

from itertools import groupby

[list(g[1]) for g in groupby(ll,key=lambda x:x is not None) if g[0]]

learningman

learningman      6 小时 1 分钟前   ❤️ 2

建议自己的作业自己写,楼上那哥们 pythonic 的写法你能理解吗

ma6254

ma6254      5 小时 22 分钟前

自己的作业自己写(滑稽

deplivesb

deplivesb      4 小时 55 分钟前

v2 已经沦陷为百度知道了吗

stimw

stimw      3 小时 46 分钟前 via Android

为什么大半年前就在问作业了...大半年后还停留在这种问题

bytesfold

bytesfold      3 小时 20 分钟前

@learningman 并不觉得 pythonic ,如果是公司代码不加备注基本无法维护

JasonEWNL

JasonEWNL      2 小时 52 分钟前

@deplivesb 高级点,Way to Overflow 。(

@going 话说回来鉴于是作业,或可回归不依赖任何库的一般思路,日后有机会亦能写出不一定最具效率但较易维护的代码。

```
il = [1, 2, None, None, None, None, None, None, 3, 4, 5, 6, None, None, None, None, 7, 8, 9, 10]
ol = [[]]
for i in il:
if i:
ol[-1].append(i)
elif ol[-1]:
ol.append([])
print(ol) # [[1, 2], [3, 4, 5, 6], [7, 8, 9, 10]]
```

keepeye

keepeye      1 小时 56 分钟前

遍历一遍不就可以了吗?这题是送分题

cnrting

cnrting      1 小时 47 分钟前 via iPhone

print(il[0:2],il[8:12],il[16:20]) 🐶

raycool

raycool      1 小时 41 分钟前

@princelai 学习了,以前还真少用这个 groupby

fml87

fml87      1 小时 10 分钟前

lst = [1,2,None,None,None,None,None,None,3,4,5,6,None,None,None,None,7,8,9,10]

[*map(eval,re.split(",,+",re.sub("[^0-9,]", "",str(lst) )))]

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK