gpt4 book ai didi

python - 对两个数字范围进行合并和排序

转载 作者:行者123 更新时间:2023-12-01 08:50:53 24 4
gpt4 key购买 nike

在此代码中,计算兰伯特制图投影中的子午线距离,我需要将 x 和 x2 的范围计算合并到一个简化的计算中。

x 的结果 >= 0
x2 的结果是 <= 0

如何将 x 和 x2 的范围计算合并为一个?首选结果将从最低负数开始,以最高正数结束,并将作为输出出现。

我不确定是否可以在此处的输出上使用排序()。我还可以根据结果创建一个列表,然后简单地调用 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

最佳答案

正如您所猜测的,您可以正常添加它们,并在将它们转换为列表后对其应用sortedsorted 默认按升序排序,

# 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))

关于python - 对两个数字范围进行合并和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53137117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com