简体   繁体   English

Python:检查数字中的条件,以列表中的130 *开头

[英]Python :Check condition in a number to starts with 130* in a list

Lets see i have a condition : 让我看看有一个条件:

a = int(b) >= 1230 and int(b) not in [1300, 1305, 1250]

Here,the list could have multiple values [1300,1303,1306,1307] etc. So i want to check: 在这里,列表可能有多个值[1300,1303,1306,1307]等。因此,我想检查一下:

if int(b) >= 1230 and int(b) = 130* and int(b) != 1250:
    do something
else:
    so something

How can i check for the numbers starting 130*? 如何检查以130 *开头的数字?

How about 怎么样

if int(b) >= 1230 and str(b).startswith('130') and int(b) != 1250:
    do something
else:
    do something

You can check if a number is inside a range() if you have a continious range to cover. 如果您要覆盖的范围很大,则可以检查数字是否在range()内。 Do not convert to int multiple times, store your int value: bAsInt = int(b) and use that. 不要多次转换为int,请存储int值: bAsInt = int(b)并使用该值。

If you want to check against specific single values, use a set() if you have 4 or more values - it is faster that a list-lookup: 如果要检查特定的单个值,请使用set()(如果有4个或更多值)-列表查找速度更快:

even = {1300,1302,1304,1306,1308}

for number in range(1299,1311):
    # print(number," is 130* :", number//10 == 130 ) # works too, integer division
    print(number," is 130* :", number in range(1300,1310), 
          " and ", "even" if number in even else "odd")

Output: 输出:

1299  is 130* : False  and  odd
1300  is 130* : True  and  even
1301  is 130* : True  and  odd
1302  is 130* : True  and  even
1303  is 130* : True  and  odd
1304  is 130* : True  and  even
1305  is 130* : True  and  odd
1306  is 130* : True  and  even
1307  is 130* : True  and  odd
1308  is 130* : True  and  even
1309  is 130* : True  and  odd
1310  is 130* : False  and  odd

Take value from user and compare : 从用户那里获取价值并进行比较

Could be solved like so: 可以这样解决:

def inputNumber():
    # modified from other answer, link see below       
    while True:
        try:
            number = int(input("Please enter number: "))
        except ValueError:
            print("Sorry, I didn't understand that.")
            continue
        else:
            return number

b = inputNumber()

even = {1300,1302,1304,1306,1308}

if b > 1230 and b not in even and b in range(1300,1310):
    #  r > 1230 is redundant if also b in range(1300,1310)
    print("You won the lottery")

It will print smth for 1301,1303,1305,1307,1309 (due to the in even ) . 它将打印1301、1303、1305、1307、1309的smth(由于in even )。


Other answer: Asking the user for input until they give a valid response 其他答案: 要求用户提供输入,直到他们给出有效的答复

You can also use this 你也可以用这个

def start_with(nub, start, stop):
    return [x for x in range(start,stop) if str(x).startswith(str(nub))]

print(start_with(130, 1, 5000))

use of this function you can find any list start with any number 使用此功能,您可以找到以任何数字开头的任何列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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