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

I am flatting the 2D list to 1D, but I can format it. I know the (v) is a list, and I tried to use for loop to print it, but I still can't get the result I want. I am wondering are there any ways to format the list. I want to print the (v) as a result with two decimal places. Like this

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

I am using the Eclipse and Python 3.0+.

m00am
  • 5,910
  • 11
  • 53
  • 69

5 Answers5

3

You could use:

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

Note that you can flatten your list using itertools.chain:

import itertools
v = list(itertools.chain(*values))
sirfz
  • 4,097
  • 23
  • 37
0

You can first flatten the list (as described here) and then use round to solve this:

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]

This can be written shorter if we put the rounding directly into the list comprehension:

print([round(number, 2) for sublist in l for number in sublist])
Community
  • 1
  • 1
m00am
  • 5,910
  • 11
  • 53
  • 69
0

I would use the built-in function round(), and while I was about it I would simplify your for loops:

def flatten(values):
    new_values = []
    for i in values:
        for v in i:
            new_values.append(round(v, 2))
    return new_values
cdarke
  • 42,728
  • 8
  • 80
  • 84
0

How to flatten and transform the list in one line

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

It returns a list of two decimals after the comma.

HolyDanna
  • 609
  • 4
  • 13
0

One you have v you can use a list comprehension like:

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

output was as follows:

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

Hope that helps!