仅当列表的元素为数字7时,列表才会停止 [英] list only stops once the element of the list is the number 7

查看:72
本文介绍了仅当列表的元素为数字7时,列表才会停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个包含子列表的代码,该子列表仅在列表的元素为某个数字(例如9)后才停止.

I want to write a code that contains a sublist , that only stops once the element of the list is a certain number , for example 9.

我已经尝试过使用其他运算符if语句.

I´ve already tried using different operators , if statements .

def sublist (list): 
return [x for x in list if x  <9]

[7,8,3,2,4,9,51] 上面列表的输出应为: [7,8,3,2,4]

[7,8,3,2,4,9,51] the output for the list above should be : [7,8,3,2,4]

推荐答案

列表推导确实用于制作映射/过滤组合.如果长度取决于迭代中的某些先前状态,则最好使用for循环,它会更易读.但是,这是itertools.takewhile的用例.这是完成此任务的一种实用方法,只是出于娱乐目的,有些甚至可能认为它可读性:

List comprehensions really are for making mapping/filtering combinations. If the length depends on some previous state in the iteration, you're better off with a for-loop, it will be more readable. However, this is a use-case for itertools.takewhile. Here is a functional approach to this task, just for fun, some may even consider it readable:

>>> from itertools import takewhile
>>> from functools import partial
>>> import operator as op
>>> list(takewhile(partial(op.ne, 9), [7,8,3,2,4,9,51]))
[7, 8, 3, 2, 4]

这篇关于仅当列表的元素为数字7时,列表才会停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆