四舍五入到 Python 3.6 中的特定数字
Rounding to specific numbers in Python 3.6
我正在尝试进行潜水 table,其中一些数字不在我能看到的模式中,因此我必须手动添加所有值,但我需要获取输入并将其四舍五入到字典中最接近的数字。
我需要将输入转换回字符串才能使输出正确:
代码:
class DepthTable:
def __init__(self):
self.d35 = {"10": "A",
"19": "B",
"25": "C",
"29": "D",
"32": "E",
"36": "F",
}
def getpressureGroup(self, depth, time):
if depth == "35":
output = self.d35[time]
else:
output = "No info for that depth"
print(output)
if __name__ == "__main__":
depthtable = DepthTable()
print("Please enter Depth (Use numbers!)")
depth = input()
print("Please Enter time!")
time = input()
depthtable.getpressureGroup(depth,time)
所以当 "player" 输入时间数字 15 时,我需要将它四舍五入到 19(即使它是 13 或类似的数字也总是向上。)我不知道我该怎么做这与 round() 或者我可能必须创建一个函数来检查每个数字..
对于大型列表,请使用标准的二分法模块或任何其他二分法包。
查看友好的 python 文档,了解如何使用 bisect
解决任务的确切说明
https://docs.python.org/2/library/bisect.html#other-examples
如果你有 numpy,试试 digitize,似乎比 pandas cut
更容易
Python: Checking to which bin a value belongs
然而对于这么短的列表,我只会使用简单的分支
if 1<x<=18:
...
elif 18<x<=28:
...
elif
或者,为了更快地构建 case by case 数组或字典
{“1”:“19”,“2”:“19”...“20”:“25”...}以编程方式,
用 activestate 字典反演片段说
http://code.activestate.com/recipes/415100-invert-a-dictionary-where-values-are-lists-one-lin/
def invert(d):
return dict( (v,k) for k in d for v in d[k] )
d35 = {"10": "A",
"19": "B",
"25": "C",
"29": "D",
"32": "E",
"36": "F",
}
dlist = d35.keys().sort()
d1 = {}
low = -1
for n in dlist[1:]:
up = int(n) + 1
interval = range(low, up)
low = up
d1[ dlist[i] ] = map(str, interval)
result = invert(d1)
您可以尝试使用 pandas
模块中的 cut
。
或多或少,它将连续变量分成离散类别,就像深度分成压力组。
您需要指定一个 bin 数组以将数据切割到其中,然后您可以对其进行标记。
所以,举个例子:
import pandas as pd
import numpy as np
timestocut = [0, 4, 8, 12, 16, 20, 24, 28, 32, 36]
pd.cut(timestocut, bins = np.array([-1,10,19,25,29,32, np.inf]), labels = np.array(['A','B','C','D','E','F']), right = True)
给予:
[A, A, A, B, B, C, C, D, E, F]
Categories (6, object): [A < B < C < D < E < F]
您可以看到 bins 有 -1,所以我们包括 0,并且 np.inf
捕捉无限大的任何东西。
将它集成到您的代码中取决于您 - 我个人会删除 dict 并使用此映射。
将 d35
字典转换为排序列表并单步执行:
In [4]: d35 = {"10": "A",
...: "19": "B",
...: "25": "C",
...: "29": "D",
...: "32": "E",
...: "36": "F",
...: }
In [5]: sorted(d35.items())
Out[5]: [('10', 'A'), ('19', 'B'), ('25', 'C'), ('29', 'D'), ('32', 'E'), ('36', 'F')]
In [7]: time = 15
In [11]: for max_time, group_name in sorted(d35.items()):
...: if int(max_time) >= time:
...: break
...:
In [12]: max_time
Out[12]: '19'
In [13]: group_name
Out[13]: 'B'
修改你的方法给出了这个。我在 for 循环中添加了一个 else 来处理未被任何组覆盖的时间。
def getpressureGroup(self, depth, time):
if depth == "35":
for max_time, group_name in sorted(self.d35.items()):
if int(max_time) >= time:
output = group_name
break
else:
output = "No info for that depth"
else:
output = "No info for that depth"
print(output)
虽然 bisect
and pandas.cut
(as mentioned in other answers) will work, you could do it with just vanilla Python (no imported modules) by looping through the cutoff values. (This is the approach in ,只是作为一个程序而不是交互式会话呈现。)
d35 = {
10: "A",
19: "B",
25: "C",
29: "D",
32: "E",
36: "F",
}
def pressure_group(time):
for cutoff in sorted(d35.items()):
if cutoff[0] >= time:
return cutoff[1]
return None # or pick something else for "too high!"
这比使用提到的模块要冗长一点,但可能更容易理解和理解正在发生的事情,因为你是自己做的(我认为这通常是个好主意,特别是如果你是尝试学习编程)。
每次循环,cutoff
都是来自 d35
字典的一对。由于这些对是从最低到最高排序的,您可以只在第一个大于或等于输入的对停止。如果循环结束(因为输入高于最高截止值),我选择 return None
,但您可以 return 其他值,或引发异常。
使用您对 "function that checks EVERY number" 的想法,实例变量 keys
可用于获取密钥(如果存在)或下一个最高密钥:
class DepthTable:
def __init__(self):
self.d35 = {10: "A",
19: "B",
25: "C",
29: "D",
32: "E",
36: "F",
}
self.keys = self.d35.keys()
def getpressureGroup(self, depth, time):
if depth == 35:
rtime = min([x for x in self.keys if x >= time]) # if exists get key, else get next largest
output = self.d35[rtime]
else:
output = "No info for that depth"
print(output)
if __name__ == "__main__":
depthtable = DepthTable()
print("Please enter Depth (Use numbers!)")
depth = int(input())
print("Please Enter time!")
time = int(input())
depthtable.getpressureGroup(depth,time)
演示:
Please enter Depth (Use numbers!)
35
Please Enter time!
13
B
Please enter Depth (Use numbers!)
35
Please Enter time!
19
B
Please enter Depth (Use numbers!)
35
Please Enter time!
10
A
我正在尝试进行潜水 table,其中一些数字不在我能看到的模式中,因此我必须手动添加所有值,但我需要获取输入并将其四舍五入到字典中最接近的数字。
我需要将输入转换回字符串才能使输出正确:
代码:
class DepthTable:
def __init__(self):
self.d35 = {"10": "A",
"19": "B",
"25": "C",
"29": "D",
"32": "E",
"36": "F",
}
def getpressureGroup(self, depth, time):
if depth == "35":
output = self.d35[time]
else:
output = "No info for that depth"
print(output)
if __name__ == "__main__":
depthtable = DepthTable()
print("Please enter Depth (Use numbers!)")
depth = input()
print("Please Enter time!")
time = input()
depthtable.getpressureGroup(depth,time)
所以当 "player" 输入时间数字 15 时,我需要将它四舍五入到 19(即使它是 13 或类似的数字也总是向上。)我不知道我该怎么做这与 round() 或者我可能必须创建一个函数来检查每个数字..
对于大型列表,请使用标准的二分法模块或任何其他二分法包。 查看友好的 python 文档,了解如何使用 bisect
解决任务的确切说明https://docs.python.org/2/library/bisect.html#other-examples
如果你有 numpy,试试 digitize,似乎比 pandas cut
更容易Python: Checking to which bin a value belongs
然而对于这么短的列表,我只会使用简单的分支
if 1<x<=18:
...
elif 18<x<=28:
...
elif
或者,为了更快地构建 case by case 数组或字典 {“1”:“19”,“2”:“19”...“20”:“25”...}以编程方式,
用 activestate 字典反演片段说
http://code.activestate.com/recipes/415100-invert-a-dictionary-where-values-are-lists-one-lin/
def invert(d):
return dict( (v,k) for k in d for v in d[k] )
d35 = {"10": "A",
"19": "B",
"25": "C",
"29": "D",
"32": "E",
"36": "F",
}
dlist = d35.keys().sort()
d1 = {}
low = -1
for n in dlist[1:]:
up = int(n) + 1
interval = range(low, up)
low = up
d1[ dlist[i] ] = map(str, interval)
result = invert(d1)
您可以尝试使用 pandas
模块中的 cut
。
或多或少,它将连续变量分成离散类别,就像深度分成压力组。
您需要指定一个 bin 数组以将数据切割到其中,然后您可以对其进行标记。
所以,举个例子:
import pandas as pd
import numpy as np
timestocut = [0, 4, 8, 12, 16, 20, 24, 28, 32, 36]
pd.cut(timestocut, bins = np.array([-1,10,19,25,29,32, np.inf]), labels = np.array(['A','B','C','D','E','F']), right = True)
给予:
[A, A, A, B, B, C, C, D, E, F]
Categories (6, object): [A < B < C < D < E < F]
您可以看到 bins 有 -1,所以我们包括 0,并且 np.inf
捕捉无限大的任何东西。
将它集成到您的代码中取决于您 - 我个人会删除 dict 并使用此映射。
将 d35
字典转换为排序列表并单步执行:
In [4]: d35 = {"10": "A",
...: "19": "B",
...: "25": "C",
...: "29": "D",
...: "32": "E",
...: "36": "F",
...: }
In [5]: sorted(d35.items())
Out[5]: [('10', 'A'), ('19', 'B'), ('25', 'C'), ('29', 'D'), ('32', 'E'), ('36', 'F')]
In [7]: time = 15
In [11]: for max_time, group_name in sorted(d35.items()):
...: if int(max_time) >= time:
...: break
...:
In [12]: max_time
Out[12]: '19'
In [13]: group_name
Out[13]: 'B'
修改你的方法给出了这个。我在 for 循环中添加了一个 else 来处理未被任何组覆盖的时间。
def getpressureGroup(self, depth, time):
if depth == "35":
for max_time, group_name in sorted(self.d35.items()):
if int(max_time) >= time:
output = group_name
break
else:
output = "No info for that depth"
else:
output = "No info for that depth"
print(output)
虽然 bisect
and pandas.cut
(as mentioned in other answers) will work, you could do it with just vanilla Python (no imported modules) by looping through the cutoff values. (This is the approach in
d35 = {
10: "A",
19: "B",
25: "C",
29: "D",
32: "E",
36: "F",
}
def pressure_group(time):
for cutoff in sorted(d35.items()):
if cutoff[0] >= time:
return cutoff[1]
return None # or pick something else for "too high!"
这比使用提到的模块要冗长一点,但可能更容易理解和理解正在发生的事情,因为你是自己做的(我认为这通常是个好主意,特别是如果你是尝试学习编程)。
每次循环,cutoff
都是来自 d35
字典的一对。由于这些对是从最低到最高排序的,您可以只在第一个大于或等于输入的对停止。如果循环结束(因为输入高于最高截止值),我选择 return None
,但您可以 return 其他值,或引发异常。
使用您对 "function that checks EVERY number" 的想法,实例变量 keys
可用于获取密钥(如果存在)或下一个最高密钥:
class DepthTable:
def __init__(self):
self.d35 = {10: "A",
19: "B",
25: "C",
29: "D",
32: "E",
36: "F",
}
self.keys = self.d35.keys()
def getpressureGroup(self, depth, time):
if depth == 35:
rtime = min([x for x in self.keys if x >= time]) # if exists get key, else get next largest
output = self.d35[rtime]
else:
output = "No info for that depth"
print(output)
if __name__ == "__main__":
depthtable = DepthTable()
print("Please enter Depth (Use numbers!)")
depth = int(input())
print("Please Enter time!")
time = int(input())
depthtable.getpressureGroup(depth,time)
演示:
Please enter Depth (Use numbers!)
35
Please Enter time!
13
B
Please enter Depth (Use numbers!)
35
Please Enter time!
19
B
Please enter Depth (Use numbers!)
35
Please Enter time!
10
A