在这段代码中,这是Lambert制图投影中子午线距离的计算,我需要将x和x2的距离计算合并到一个简化的计算中。
x的结果> = 0
x2的结果是<= 0
如何将x和x2的范围计算合并为一个?首选结果将以最低的负数开始,以最高的正数结束,并将其作为输出输出。
我不确定是否可以在此处的输出上使用sorted()。我也可以从结果中列出一个列表,然后简单地调用list.sort(),但是凭我的代码知识,我不确定如何正确编写它。
代码如下:
if projection == "L":
print("Lambert projection")
s = int(input("Define scale 1:(input)"))
if s <= 0:
sys.exit("scale must have higher value than 0")
v = int(input("Define longitude interval of meridians"))
if v <= 0:
sys.exit("Interval must have higher value than 0")
n = int(input("How many meridians to project? (from center)"))
if n <=0:
sys.exit("Number must be higher than 0")
for v in range(n):
x = R*(v*n)
if x/s<100:
print("meridian will be", x/s, "cm from center")
else:
print("meridian will be - cm from center")
for v in range(n):
x2 = R*(-v*n)
print("meridian will be", x2/s, "cm from center")
我现在从范围中得到的结果:
meridian will be 0.0 cm from center
meridian will be 1.1467998 cm from center
meridian will be 2.2935996 cm from center
meridian will be 3.4403994 cm from center
meridian will be 0.0 cm from center
meridian will be -1.1467998 cm from center
meridian will be -2.2935996 cm from center
meridian will be -3.4403994 cm from center
预期结果:
meridian will be -3.4403994 cm from center
meridian will be -2.2935996 cm from center
meridian will be -1.1467998 cm from center
meridian will be 0.0 cm from center
meridian will be 1.1467998 cm from center
meridian will be 2.2935996 cm from center
meridian will be 3.4403994 cm from center
答案 0 :(得分:1)
您可以将它们转换为列表后,正常添加它们并对其应用sorted
。 sorted
默认按升序排序,
# initialize lists at the top of your code,
l1 = []
l2 = []
然后您可以在每次迭代时将其附加到两个列表中,
替换
x = R*(v*n)
if x/s<100:
print("meridian will be", x/s, "cm from center")
使用
x = R*(v*n)
if x/s<100:
l1.append(x/s)
对x2
最后创建一个排序列表,
sorted_list = sorted(l1 + l2)
打印排序列表,
for i in sorted_list:
print("meridan will be {}".format(i))
答案 1 :(得分:0)
您可以尝试使用列表理解功能。
x = list(map(lambda v: R * (v * n) / s, range(n)))
x.extend(map(lambda v: R * (-v * n) / s, range(n)))
x = list(filter(lambda v: v < 100, x))
x_sorted = sorted(x)
我在这里所做的工作是使用extend
方法,该方法与使用__add__
运算符的工作原理类似,只不过extend不会创建新列表,而是向当前列表添加值,这意味着有点快。另外,列表理解通常比Python中的循环更快,并且更易于阅读引导。
因此,如果您使用R = 6371.11
,s = 100000
和n = 18
运行,则应该得到:
[-19.4955966, -18.3487968, -17.201997, -16.0551972, -14.9083974, -13.7615976, -12.6147978,
-11.467998, -10.3211982, -9.1743984, -8.0275986, -6.8807988, -5.733999, -4.5871992,
-3.4403994, -2.2935996, -1.1467998, 0.0, 0.0, 1.1467998, 2.2935996, 3.4403994, 4.5871992,
5.733999, 6.8807988, 8.0275986, 9.1743984, 10.3211982, 11.467998, 12.6147978, 13.7615976,
14.9083974, 16.0551972, 17.201997, 18.3487968, 19.4955966]