相关疑难解决方法(0)

如何检测列表的非数量?

假设我有一个列表如下:

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)

但它看起来如此冗长且难以理解,所以任何人都有更好的方法来检测它?

另外,我的列表包含负数和负数字的字符串,我该怎么办?

python list

4
推荐指数
1
解决办法
1054
查看次数

什么是测试输入是格式良好的数字的最pythonic方式

我有一个函数,它期望实数(整数或浮点数)作为它的输入,我试图在对它进行数学运算之前验证这个输入.

我的第一直觉是将输入作为浮点数从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) )但"所有这些可能是数字"的清单对我来说似乎有点不合适.

最狡猾的方式是什么?我忽略了另一种选择吗?

python idioms

2
推荐指数
2
解决办法
520
查看次数

检查用户输入是否为数字

我正在尝试比较用户收到的输入,检查输入是否实际上是一个数字.这是我到目前为止所拥有的:

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)

python

2
推荐指数
2
解决办法
2434
查看次数

python if-elif-else总是去其他地方

我认为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)

python python-3.x

2
推荐指数
1
解决办法
566
查看次数

在python中将字符串列表转换为不同的数据类型

我想知道是否有更简洁的方法来解析以下字符串:

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)

python split casting

2
推荐指数
2
解决办法
180
查看次数

在Python中检查变量是否为数字类型的最佳方法是什么

我知道我可以使用type()和isinstance()来检查变量是否属于某种类型或属于某个类。我想知道是否有一种快速的方法来检查变量是否为“数字”类型,类似于MATLAB中的isnumeric。如果变量是int,long,float,double,int或float数组等,则应返回True。非常感谢任何建议。

谢谢。

python types

1
推荐指数
1
解决办法
568
查看次数

检查用户是否输入了数字.不要信

我想知道检查用户键入字母与数字的最简单方法.如果用户输入一个字母,它会给他们一个错误信息并回答他们的问题.现在我拥有它,所以当用户输入'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)

我需要它回到问路站的问题.

python

0
推荐指数
1
解决办法
2047
查看次数

如果数字是'字符串',如何检查数字是否为数字?

这是一个更大的计划的一部分.这是我想要做的.

  1. 将句子传递给扫描方法.
  2. 请句子包含数字.
  3. 将句子分成不同的术语.
  4. 将一个元组附加到列表中,元组中的第一个表达式是单词或句子元素所适合的类型,第二个是单词或数字.

这是我正在尝试的:

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 types integer

0
推荐指数
1
解决办法
576
查看次数

Python字符串函数

如何确定字符串在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)

python string integer boolean digit

0
推荐指数
1
解决办法
1151
查看次数

确保输入是一个浮点数

我目前的代码:

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)

python input python-3.x

0
推荐指数
1
解决办法
50
查看次数

字符串到 int ValueError Python

如果字符串是 '007w',那么当它尝试将 '007w' 作为整数返回时,我希望它return Noneprint('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)

python types valueerror

0
推荐指数
1
解决办法
144
查看次数

标签 统计

python ×11

types ×3

integer ×2

python-3.x ×2

boolean ×1

casting ×1

digit ×1

idioms ×1

input ×1

list ×1

split ×1

string ×1

valueerror ×1