I have a generator which yields to datatype on is decimal and other is string i need the method to just return the decimal
JavaScript
x
11
11
1
def my_generator():
2
yield amount, name
3
4
5
def get_amount(obj):
6
p = list()
7
gen = obj.my_generator()
8
for i in gen:
9
p.append(i)
10
return p
11
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
Advertisement
Answer
Simply get only the first value from your tuple with i[0]
.
Example:
JavaScript
1
15
15
1
from decimal import Decimal
2
from random import randint
3
4
def my_generator(count):
5
for _ in range(count):
6
yield Decimal(randint(1000, 2000)), "some str"
7
8
def get_amount(count):
9
p = []
10
for i in my_generator(count):
11
p.append(f'${i[0]:0,.2f}')
12
return p
13
14
print(get_amount(2))
15
Output:
JavaScript
1
2
1
['$1,638.00', '$1,685.00']
2
Here’s a more verbose version of the for loop, also using str.format instead of f-string
JavaScript
1
5
1
for i in my_generator(count):
2
money, unused_str_value = i # assign tuple values to individual variable names
3
formatted_money = '${:0,.2f}'.format(money)
4
p.append(formatted_money)
5