我希望能够更改从英里到公里的距离列表,其中的里程列表在下面的代码中获得:
input_string = input("Enter a list of distances, separated by spaces").strip()
要将输入列表更改为整数列表,我使用了:
distances = input_string.split()
print("This is what you entered: ")
for distance in distances:
print(distance)
def str2int(word):
"""Converts the list of string of miles into a list of integers of miles"""
integer = int(word)
if int(word):
return integer
else:
sys.exit("Please try again and enter a list of integers.")
def validate_all(distances):
"""
Checks if all the inputs are integers. If not all are integers, sys.exit
without converting any of the distances and ask to try again.
"""
true_list = []
for distance in distances:
if str2int(distance):
true_list.append(distance)
if len(distances) == len(true_list):
return True
else:
return False
print("And now, we are going to convert the first one to kilometers:")
miles = distances[0]
if validate_all:
# now, the calculation and display
kms = miles_int * KMPERMILE
print("The first distance you entered, in kilometers:", kms)
for i in range(1, len(distances), 1):
miles_int = str2int(distances[i])
kms = miles_int * KMPERMILE
print("The next distance you entered in kilometres:", kms)
但是,当我尝试检查字符串列表中的所有元素是否都可以更改为整数(使用validate_all(word))并且具有类似
的内容时12 23 apples banana 5
作为我的输入,程序崩溃说
有值错误str2int(word)
-> if int(word):
而不是我获取sys.exit
任何人都可以为我调试这个/请为我做这个吗?
答案 0 :(得分:2)
>>> t = '12 23 apples banana 5'
>>> [int(x) for x in t.split() if x.isdecimal()]
[12, 23, 5]
答案 1 :(得分:0)
您可以使用try-except
子句:
def str2int(word):
"""Converts the list of string of miles into a list of integers of miles"""
try:
integer = int(word)
return integer
except ValueError:
print "here"
sys.exit("Please try again and enter a list of integers.")
print(str2int("asd"))
<强>输出:强>
here
Please try again and enter a list of integers.
注意:强>
您可以在Python docs中详细了解处理例外情况和try-except
条款。
答案 2 :(得分:0)
您尝试if int(x): ...
,但int
不是谓词。如果x
是一个无法转换为int的字符串,则会引发ValueError
。例如,x='0'
if int(x): ...
被评估为False
,尽管它是类似int的值。
您需要的是以下谓词:
def is_int_able(x):
try:
int(x)
return True
except ValueError:
return False
有了这个,你可以这样做:
[ int(x) for x in line.split() if is_int_able(x) ]
答案 3 :(得分:0)
您的validate_all()
可以使用all()
和str.digit()
:
In [1]: all(e.isdigit() for e in ['12', '23', 'apples', 'banana', '5'])
Out[1]: False
In [2]: all(e.isdigit() for e in ['12', '23', '5'])
Out[2]: True
但也许更好的方法是取消此验证并在列表理解中使用if
过滤:
In [3]: distances = ['12', '23', 'apples', 'banana', '5']
In [4]: [int(km) * km_to_miles for km in distances if km.isdigit()]
Out[4]: [7.456454304, 14.291537416, 3.10685596]