假设我有一个列表如下:
a = ['111', 213, 74, '99', 't', '88', '-74', -74]
Run Code Online (Sandbox Code Playgroud)
该列表包含数字类型的字符串,数字和数据类型的字符串.
我认为类似数字的字符串可以转换数字,所以它可以看作一个数字.
这是我的方法:
a = ['111', 213, 74, '99', 't', '88', '-74', -74]
def detect(list_):
for element in list_:
try:
int(element)
except ValueError:
return False
return True
print detect(a)
Run Code Online (Sandbox Code Playgroud)
但它看起来如此冗长且难以理解,所以任何人都有更好的方法来检测它?
另外,我的列表包含负数和负数字的字符串,我该怎么办?
我有一个函数,它期望实数(整数或浮点数)作为它的输入,我试图在对它进行数学运算之前验证这个输入.
我的第一直觉是将输入作为浮点数从try-except块中转换出来.
try:
myinput = float(input)
except:
raise ValueError("input is not a well-formed number")
Run Code Online (Sandbox Code Playgroud)
我也可以打电话,isinstance(mydata, (float, int, long) )但"所有这些可能是数字"的清单对我来说似乎有点不合适.
最狡猾的方式是什么?我忽略了另一种选择吗?
我正在尝试比较用户收到的输入,检查输入是否实际上是一个数字.这是我到目前为止所拥有的:
numstring = input("Choose a number between 1 and 10")
Run Code Online (Sandbox Code Playgroud)
然后比较我在这样的方法中有它:
def check(a):
if int(a) == int:
print("It's a number!")
else:
print("It's not a number!")
Run Code Online (Sandbox Code Playgroud)
它总是打印出它不是一个数字,即使它是.
这个计划的目标:我正在做一个猜谜游戏:
import random
numstring = input("Choose a number between 1 and 10")
def check(a):
if int(a) == int:
print("It's a number!")
else:
print("It's not a number!")
if abs(int(a)) < 1:
print("You chose a number less than one!")
elif abs(int(a)) > 10:
print("You chose a number more than ten!")
else:
randomnum = random.randint(1, 10)
randomnumstring …Run Code Online (Sandbox Code Playgroud) 我认为if-elif-else语句有问题,因为它总是转向其他语句
#initialize total
total=0.0
#ask for inputs
budget=float(input("Plz Enter amount that you budgeted for a month: "))
expense=float(input("Plz Enter 1st expense - to quit enter 0: "))
while expense!=0:
# Add the expense to the accumulator.
total += expense
expense=float(input("Plz Enter a expense - to quit enter 0: "))
#display results
if total>budget:
print("You are over-budget by",total-budget)
elif budget<total:
print("You have",budget-total,"to spare")
else:
print("Your budget is equal to expense")
Run Code Online (Sandbox Code Playgroud) 我想知道是否有更简洁的方法来解析以下字符串:
line = "NOVEL_SERIES, 3256432, 8, 1, 2.364, 4.5404, 9.8341"
key, id, xval, yval, est1, est2, est3 = line.split()
id = int(id)
xval = int(value1)
yval = int(value2)
est1 = float(est1)
est2 = float(est2)
est3 = float(est3)
Run Code Online (Sandbox Code Playgroud) 我知道我可以使用type()和isinstance()来检查变量是否属于某种类型或属于某个类。我想知道是否有一种快速的方法来检查变量是否为“数字”类型,类似于MATLAB中的isnumeric。如果变量是int,long,float,double,int或float数组等,则应返回True。非常感谢任何建议。
谢谢。
我想知道检查用户键入字母与数字的最简单方法.如果用户输入一个字母,它会给他们一个错误信息并回答他们的问题.现在我拥有它,所以当用户输入'q'时它将退出脚本.
if station == "q":
break
else:
#cursor.execute(u'''INSERT INTO `scan` VALUES(prefix, code_id, answer, %s, timestamp, comport)''',station)
print 'Thank you for checking into station: ', station
Run Code Online (Sandbox Code Playgroud)
我需要它回到问路站的问题.
这是一个更大的计划的一部分.这是我想要做的.
这是我正在尝试的:
def scan(self, sentence):
self.term = []
for word in sentence.split():
if word in direction:
self.term.append(('direction', word))
elif word in verbs:
self.term.append(('verb', word))
elif word in stop:
self.term.append(('stop', word))
elif word in nouns:
self.term.append(('noun', word))
elif type(int(word)) == 'int':
self.term.append(('number', int(word)))
else:
self.term.append(('error', word))
return self.term
print lexicon.scan('12 1234')
Run Code Online (Sandbox Code Playgroud)
这是一个类中的方法,print语句在外面.我关心和遇到麻烦的部分是这样的:
elif type(int(word)) == int:
self.term.append(('number', int(word)))
Run Code Online (Sandbox Code Playgroud)
它适用于任何自然数[1,无穷大]
编辑:当我尝试扫描时遇到问题('ASDFASDFASDF')
如何确定字符串在Python中是否可以是整数。例如:如果我编写名为digit()和nondigit()的函数。字符串只能是数字(1-9)或字母。
str1 = '4582'
str1.digit() == True
str2 = '458dfr'
str2.digit() == False
str3 = 'abcd'
str3.nondigit() == True
str4 = '258edcx'
str4.nondigit() == False
Run Code Online (Sandbox Code Playgroud) 我目前的代码:
while True:
surjuv = input("What is the juvenile survival rate?")
if surjuv.isinstance(float)==True and float(surjuv)<=1 and float(surjuv)>=0:
break
Run Code Online (Sandbox Code Playgroud)
它需要确保它surjuv是一个浮点数,但输入0.5时会出现以下错误:
Traceback (most recent call last):
File "python", line 81, in <module>
File "python", line 21, in main_menu
File "python", line 51, in enter_gen0
AttributeError: 'str' object has no attribute 'isinstance'
Run Code Online (Sandbox Code Playgroud) 如果字符串是 '007w',那么当它尝试将 '007w' 作为整数返回时,我希望它return None和print('Cannot be converted). 但不使用 Try 除外 ValueError:
import random
def random_converter(x):
selection = random.randint(1,5)
if selection == 1:
return int(x)
elif selection == 2:
return float(x)
elif selection == 3:
return bool(x)
elif selection == 4:
return str(x)
else:
return complex(x)
for _ in range(50):
output = random_converter('007w')
print(output, type(output))
Run Code Online (Sandbox Code Playgroud)