Home > Enterprise >  Return decimal fields from list
Return decimal fields from list

Time:10-20

I have a generator which yields to datatype on is decimal and other is string i need the method to just return the decimal

def my_generator():
    yield amount, name


def get_amount(obj):
    p = list()
    gen = obj.my_generator()
    for i in gen:
        p.append(i)
    return p

get_amount()

now it is returning [(Decimal('1950.00'), '06/16/2020'), (Decimal('4500.00'), '06/16/2020')]

I want the list to be returned as formatted how can i do that '${:0,.2f}'.format(Decimal('1950.00') which is in my list) so the end result would be like $1,950.00

if the the return has two yields it should return like. $1,950.00, $4,500.00

CodePudding user response:

Simply get only the first value from your tuple with i[0].

Example:

from decimal import Decimal
from random import randint

def my_generator(count):
    for _ in range(count):
        yield Decimal(randint(1000, 2000)), "some str"

def get_amount(count):
    p = []
    for i in my_generator(count):
        p.append(f'${i[0]:0,.2f}')
    return p

print(get_amount(2))

Output:

['$1,638.00', '$1,685.00']

Here's a more verbose version of the for loop, also using str.format instead of f-string

for i in my_generator(count):
    money, unused_str_value = i # assign tuple values to individual variable names
    formatted_money = '${:0,.2f}'.format(money)
    p.append(formatted_money)
  • Related