简体   繁体   中英

Python: “If” function

This is probably really simple but I can't figure it out.

I have a bunch of lists and I want to call certain lists if they are in the range equal to a value x and any number between x-5 and x +5. ie x-5,x-4,x-3,x-2,x-1,x,x+1,x+2,x+3,x+4 and x+5.

At the moment I have

if sum(listname[i])==x:

if sum(listname[i])==x-1:

if sum(listname[i])==x-2:

etc

How can I do it so that it is combined in one "if" function.

I've been thinking on the lines of something like:

if sum(listname[i])==x-5>=x>=x+5:

or

if sum(listname[i])==x or x-1 or x-2 ".. etc":

but neither work.

Can anybody shine some light on this?

A scenario like if sum(listname[i])==x or x-1 or x-2 ".. etc": (which is not valid python) is usually solved with if value in range(start, stop, step):

So you would write:

if sum(listname[i) in range(x-2, x):
    # Code for this case here...

Do you simply mean

if x-5 <= sum(listname[i]) <= x+5:
    ...
    ...

It looks like you want to check if the sum of the list is between x - 5 and x + 5 . To put it in one if statement is simply:

s = sum(listname[i])
if s >= x - 5 and s <= x + 5:
  # do stuff

From what I understand from your question. You what to check that whether sum(listname[i]) is between (x-5, x+5)

You can do this in a single if assuming x is a possitive value:

if (sum(listname[i]) >= (x - 5)) and (sum(listname[i]) <= (x+5))

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