[英]Python data[i] to data[i+100] < # (eg. 50)
I have a list containing a large amount of data. 我有一个包含大量数据的列表。 If I want to set a if statement as the pseudo code below: 如果我想将if语句设置为下面的伪代码:
if data[i] to data[i+100] < 50:
data[i] == 1
Is there any way that I don't need to type something like below? 我有什么办法不需要键入以下内容?
data[i] <50 and data[i+1] <50 and data[i+2] <50 and .... and data[i+100] <50:
Because it'd just be too time consuming. 因为那太浪费时间了。 If anyone knows the faster way, pls let me know. 如果有人知道更快的方法,请告诉我。 Appreciated!! 赞赏!
Yes, you can use all(..)
for that over a slicing of the list: 是的,您可以在列表的切片上使用all(..)
:
if all(x < 50 for x in data[i:i+101]):
data[i] = 1 # probably you want assignment?
You have to write i:i+101
as slicing (and not i:i+100
), since the upper bound is exclusive . 您必须将i:i+101
写为切片(而不是i:i+100
),因为上限是互斥的 。
Or you can use range(..)
and save on making a slice-copy of the list: 或者,您可以使用range(..)
并保存列表的切片副本:
if all(data[j] < 50 for j in range(i,i+101)):
data[i] = 1 # probably you want assignment?
Note that although you do not type all these conditions separately, of course Python will still perform iteration (and evaluate at most 101 such expressions). 请注意,尽管您没有单独键入所有这些条件,但是Python当然仍然会执行迭代(并最多计算 101个这样的表达式)。
Sure. 当然。 You can map
over the values, checking your requirement, and then can use all
to ensure that they meet it: 您可以map
这些值,检查您的要求,然后可以使用all
来确保它们满足要求:
>>> data = range(1000)
>>> all(map(lambda i: i < 50, data[:100]))
# => True
To break down whats going on: 要分解正在发生的事情:
data[:101]
gets a slice of the first 101 items in the array data[:101]
获取数组中前101个项目的一部分 map
iterates over those items and returns a boolean if passed our check i < 50
. map
遍历这些项目,如果通过我们的检查i < 50
,则返回一个布尔值。 ie. 即。 the resulting list is [True, True, True, ...]
结果列表为[True, True, True, ...]
all
then checks that every value is True all
然后检查每个值为True Then you can replace the items with some smart slicing: 然后,您可以使用一些智能切片来替换项目:
if all(map(lambda i: i < 50, data[:100])):
data = [1] * 100 + data[100:]
是。
if all(data[i+k] < 50 for k in range(0,101)):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.