浮点数与已知值python的比较

时间:2013-05-30 07:54:14

标签: python list comparison floating

大家好我有一个从功能

计算的列表
ab = (x, x1, x2, x3, x4, x5, x6, x7, x8)

其中x,x1等是根据距离方程计算的浮点数。有什么办法可以在列表中取出每个浮点值并将它们与已知值进行比较。我是

knowndistance = 200

并且如果该值大于已知距离打印大于且小于打印小于。然后我想收集所有小于和大于结果并将它们分成两个部分列表,其中一个是greaterthan []而另一个是lessthan []

所以我想比较ab中的所有值,看看它们是否大于是否有任何可以为我执行此操作的代码,而不是为每个语句键入if。我目前的代码在下面,但对于花车不起作用?

new_list = []
for i, x in enumerate(ab):
  if x < knowndistance:
    lessthan = "Station {} average is less than {}".format(i+1, knowndistance)


comicdb = []

record = {}
record = lessthan
comicdb.append(record)
new_list.extend(comicdb)

提前感谢您的帮助:)

2 个答案:

答案 0 :(得分:0)

列表推导可以快速为您提供一组过滤的值:

lessthan = [v for v in ab if v < knowndistance]
greaterthan = [v for v in ab if v >= knowndistance]

或使用循环对值进行分区:

lessthan, greaterthan = [], []
for v in ab:
    if v < knowndistance:
        lessthan.append(v)
    else:
        greaterthan.append(v)

请注意,此处greaterthan严格为greater then or equal to,但如果您需要忽略任何完全等于knowndistance的值,则可以收紧测试。

答案 1 :(得分:0)

如果您需要经常在代码中搜索密钥,建议您预先对数据进行排序,然后执行二进制搜索。根据查找频率和输入数据的长度,这将是有效的

>>> import bisect
>>> import random
>>> ab = [random.random()*100 for _ in range(20)]
>>> ab = sorted(ab)
>>> knowndist = 50
>>> index = bisect.bisect_left(ab, knowndist)
>>> left = ab[:index]
>>> right = ab[index:]
>>> left
[0.7247004541477753, 4.854550484568454, 5.07097854581271, 5.768240615684894, 39.99461725759485]
>>> right
[61.05798332602631, 62.49927871117734, 64.18742114760279, 64.33592616994855, 67.47713405587675, 69.82614000336153, 70.8239641304042, 73.52120950142177, 76.36583812405388, 77.21433592853452, 80.63221055514911, 82.32348252610743, 91.75223944014984, 95.04315728608329, 99.04521000455324]