打印时如何格式化列表

时间:2016-07-21 14:02:36

标签: python python-3.x

values = [[3.5689651969162908, 4.664618442892583, 3.338666695570425],
          [6.293153787450157, 1.1285723419142026, 10.923859694586376],
          [2.052506259736077, 3.5496423448584924, 9.995488620338277],
          [9.41858935127928, 10.034233496516803, 7.070345442417161]]

def flatten(values):

    new_values = []
    for i in range(len(values)):
        for v in range(len(values[0])):
            new_values.append(values[i][v])
    return new_values

v = flatten(values)
print("A 2D list contains:") 
print("{}".format(values))
print("The flattened version of the list is:")
print("{}".format(v))

我将2D列表展平为1D,但我可以对其进行格式化。我知道(v)是一个列表,我尝试使用for循环来打印它,但我仍然无法得到我想要的结果。我想知道有没有办法格式化列表。我想打印(v)作为结果有两个小数位。喜欢这个

  

[3.57,4.66,3.34,6.29,1.13,10.92,2.05,3.55,10.00,9.42,10.03,7.07]

我正在使用Eclipse和Python 3.0 +。

5 个答案:

答案 0 :(得分:3)

您可以使用:

print(["{:.2f}".format(val) for val in v])

请注意,您可以使用itertools.chain展平您的列表:

import itertools
v = list(itertools.chain(*values))

答案 1 :(得分:0)

您可以先将列表展平(as described here),然后使用round解决此问题:

flat_list = [number for sublist in l for number in sublist]
# All numbers are in the same list now
print(flat_list)
[3.5689651969162908, 4.664618442892583, 3.338666695570425, 6.293153787450157, ..., 7.070345442417161]

rounded_list = [round(number, 2) for number in flat_list]
# The numbers are rounded to two decimals (but still floats)
print(flat_list)
[3.57, 4.66, 3.34, 6.29, 1.13, 10.92, 2.05, 3.55, 10.00, 9.42, 10.03, 7.07]

如果我们将舍入直接放入列表理解中,可以写得更短:

print([round(number, 2) for sublist in l for number in sublist])

答案 2 :(得分:0)

我会使用内置函数round(),当我谈到它时,我会简化你的for循环:

def flatten(values):
    new_values = []
    for i in values:
        for v in i:
            new_values.append(round(v, 2))
    return new_values

答案 3 :(得分:0)

如何在一行中展平和转换列表

[round(x,2) for b in [x for x in values] for x in b]

它返回逗号后面的两位小数列表。

答案 4 :(得分:0)

你有一个v你可以使用列表理解,如:

formattedList = ["%.2f" % member for member in v] 

输出如下:

['3.57', '4.66', '3.34', '6.29', '1.13', '10.92', '2.05', '3.55', '10.00', '9.42', '10.03', '7.07']

希望有所帮助!