简体   繁体   中英

Comma separated List formatting

I am looking to create a list of 20 random numbers within a list but looking to print the result of these numbers comma separated. Getting an error when I am looking to format the Prinicipal list below.

res = ('{:,}'.format(Principal))
TypeError: unsupported format string passed to list.__format__.

How can I fix this?

def inventory(i,j):
    import random
    Amount = random.choices([x for x in range(i,j+1) if x%25 == 0],k=20)
    return Amount

def main():
    Principal = inventory(100000, 1000000)
    res = ('{:,}'.format(Principal))
    print('\nInventory:\n', + str(res))
    minAmt = min(Principal)
    maxAmt = max(Principal)

    res1 = ('{:,}'.format(minAmt))
    res2 = ('{:,}'.format(maxAmt))
    print('\nMin amount:' + str(res1))
    print('\nMax amount:' + str(res2))

if __name__ == '__main__':
    main()

You are looking for str.join . Eg

res = ','.join(map(str, Principal))

Also, the following is not a valid syntax:

print('\nInventory:\n', + str(res))

The + there is illegal.

Principal is a list of amounts and , is not a format specifier for lists. Print each amount individually:

import random

def inventory(i,j):
    return random.choices([x for x in range(i,j+1) if x%25 == 0],k=20)

amounts = inventory(100000, 1000000)
print('\nInventory:\n')
for amount in amounts:
    print(f'{amount:,}')

print(f'\nMin amount: {min(amounts):,}')
print(f'\nMax amount: {max(amounts):,}')

Output:

Inventory:

283,250
904,600
807,800
297,850
314,000
557,450
167,550
407,475
161,550
684,225
787,025
513,975
252,750
217,500
394,200
777,475
621,575
888,625
895,525
846,650

Min amount: 161,550

Max amount: 904,600

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM