列表中的舍入数字为2sf

时间:2018-04-16 06:12:28

标签: python

我是python的新手,我在列表中有一组数据会输出以下内容:

[(['S1'], 123.6, 4, -3.09710082168993), (['S2'], 189.6, 4, -3.09710082168993)]
[(['S1'], 123.6, 4, -1974.1075190129), (['S2'], 189.6, 4, -1974.1075190129)]

我通过以下代码获得此输出:

plateX = g_o.getresults(phase, g_o.ResultTypes.NodeToNodeAnchor.X, 'node') 
plateY = g_o.getresults(phase, g_o.ResultTypes.NodeToNodeAnchor.Y, 'node') 
plateM = g_o.getresults(phase, g_o.ResultTypes.NodeToNodeAnchor.AnchorForce2D, 'node')
layer = (
['S1'],
['S2'],    
['S3'],
['S4'],
['S5'],
['S6'],)

result = zip(layer, plateX, plateY, plateM)
test1 = list(result)
print(test1)

我应该如何完成结果但保留" S1" ," S2"作为结果的指标?
感谢您的帮助。

E.g.
[(['S1'], 123.6, 4, -3.09710082168993), (['S2'], 189.6, 4, -3.09710082168993)]
to
[(['S1'], 123.6, 4, -3.1), (['S2'], 189.6, 4, -3.1)]

这就是我想要实现的目标。

3 个答案:

答案 0 :(得分:0)

编辑此行:

result = zip(layer, plateX, plateY, round(plateM, 2))

你可以使用round函数,它将数字作为第一个参数,第二个参数是精度。

答案 1 :(得分:0)

将元组转换为列表,然后对元素进行舍入。

d = [(['S1'], 123.6, 4, -3.09710082168993), (['S2'], 189.6, 4, -3.09710082168993)]
d = list(map(list, d))              #Convert to list.
for i in d:
    i[-1] = round(i[-1], 2)      #round value.
d = list(map(tuple, d))             #Convert to tuple.
print(d)

<强>输出:

[(['S1'], 123.6, 4, -3.1), (['S2'], 189.6, 4, -3.1)]

答案 2 :(得分:0)

您可以使用生成器

对它们进行舍入
result = zip(layer, plateX, plateY, (round(x, 2) for x in plateM))

为解释器节省内存和工作