简体   繁体   中英

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 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:

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 .

Or you can use range(..) and save on making a slice-copy of the list:

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).

Sure. You can map over the values, checking your requirement, and then can use all to ensure that they meet it:

>>> 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
  • map iterates over those items and returns a boolean if passed our check i < 50 . ie. the resulting list is [True, True, True, ...]
  • all then checks that every value is 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)):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM