如何使布尔表达式更短?或或或或

时间:2012-02-05 12:04:16

标签: python boolean-expression

var = raw_input()

if "0" in var or "1" in var or "2" in var or "3" in var or "4" in var or "5" in var or "6" in var or "7" in var or "8" in var or "9" in var:
    print "yay"
else:
    print: ":("

有没有办法让我更短,不必写所有数字?如果它是(0,10),那就好了,如果它是(0,10000)

是否有可能以某种方式使用列表?

7 个答案:

答案 0 :(得分:12)

any(str(i) in var for i in range(10))

答案 1 :(得分:5)

在这种情况下,正则表达式非常简洁:

import re
if re.search(r"\d", str):
  print "yay"
else
  print ":("

甚至更短:

print "yay" if re.search(r"\d", str) else ":("

答案 2 :(得分:4)

  

我想确保字符串中有一个数字然后将其转换为整数。另外我需要确保没有其他符号,但字符串中的数字

为此,您可以将int()应用于您已阅读的字符串,捕获ValueError例外:

def read_int(prompt):
    while True:
        var = raw_input(prompt)
        try:
            val = int(var)
            if val > 0: return val
            print 'the number must be positive, try again'
        except ValueError as ex:
            print 'invalid number, try again'

print read_int('enter a positive integer: ')

答案 3 :(得分:1)

最好的答案肯定是

print 'yay' if any(c in '0123456789' for c in var) else ':('

任何人都会很容易理解为什么

编辑1

不,这不是最佳答案,因为它是以下方法中最慢的一种 我喜欢正则表达式,但我无法想象使用正则表达式的解决方案将是最快的 即使使用set()也更快。

var = '''For all his fame and celebration, William Shakespeare remains a mysterious figure
with regards to personal history. There are just two primary sources for information
on the Bard: his works, and various legal and church documents that have survived from
Elizabethan times. Naturally, there are many gaps in this body of information, which
tells us little about Shakespeare the man. 
William Shakespeare was born in Stratford-upon-Avon, allegedly on April 23, 1564.'''

from time import clock
import re


n = 1000


te = clock()
for i in xrange(n):
    b = any(c in ('0123456789') for c in var)
print clock()-te


ss = set('0123456789')
te = clock()
for i in xrange(n):
    b = ss.intersection(var)
print clock()-te


te = clock()
for i in xrange(n):
    b = re.search('\d',var)
print clock()-te


regx = re.compile('\d')
te = clock()
for i in xrange(n):
    b = regx.search(var)
print clock()-te

结果

0.157774521622
0.0335822010898
0.0178648403638
0.00936152499829

编辑2

由Jove!
事实上, shensei 的回答是最好的答案 恰恰相反于我的想象!

from time import clock
import re


n = 1000

te = clock()
for i in xrange(n):
    b = any(dig in var for dig in '0123456789')
print clock()-te

结果

0.00467852757823

我的结论是,for dig in var var 的探索确实超级超快。
我只知道它非常快。

编辑3

没有人指出shensei解决方案的执行时间取决于分析字符串的内容:

from time import clock
n = 1000

var = '''For all his fame and celebration, William Shakespeare remains a mysterious figure
with regards to personal history. There are just two primary sources for information
on the Bard: his works, and various legal and church documents that have survived from
Elizabethan times. Naturally, there are many gaps in this body of information, which
tells us little about Shakespeare the man. 
William Shakespeare was born in Stratford-upon-Avon, allegedly on April 00, 0000.'''

te = clock()
for i in xrange(n):
    b = any(dig in var for dig in '0123456789')
print clock()-te 

var = '''For all his fame and celebration, William Shakespeare remains a mysterious figure
with regards to personal history. There are just two primary sources for information
on the Bard: his works, and various legal and church documents that have survived from
Elizabethan times. Naturally, there are many gaps in this body of information, which
tells us little about Shakespeare the man. 
William Shakespeare was born in Stratford-upon-Avon, allegedly on April 99, 9999.'''

te = clock()
for i in xrange(n):
    b = any(dig in var for dig in '0123456789')
print clock()-te 

给出结果

0.0035278226702
0.0132472143806

在最坏的情况下,使用ompiled正则表达式需要0.00936152499829秒似乎比shensei的解决方案更快。但事实上,如果编制正则表达式的时间包含在时​​间测量中,则实际执行的时间为0.0216940979929秒。 那么shensei的解决方案仍然是最快的方法。

答案 4 :(得分:0)

根据'var'的大小和值的数量,您可能最好使用集合。

values = set(map(str, range(10000)))
print(not set(var).isdisjoint(values))

如果var = raw_input()有10000个值没有意义,但我想你还有另一个用例。

答案 5 :(得分:0)

var = raw_input()
list_of_strings = map(str, range(10))
if var in list_of_strings:
    print 'yay!'
else:
    print ':('

或者,将raw_input转换为字符串:

try:
    var = int(raw_input())
except ValueError as e:
    var = int(raw_input('Please enter a number!'))
if var in range(10):
    print 'yay'
else:
    print ':('

注意:我的第一个示例需要额外的步骤将数字列表转换为字符串列表。我的第二个例子是相反的方式,并将输入从字符串转换为数字。

答案 6 :(得分:0)

从OP评论:“”“我想确保字符串中有一个数字,然后将其转换为整数。另外我需要确保没有其他符号,但字符串中的数字 - ”“”

这在Python中是微不足道的:   只需要做“var.isdigit()” - .isdigit是一个字符串方法。

从字符串中提取数字的推荐方法是:

try:
    result = int(var)
except ValueError:
    # put error handler code here