Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating sublists with ":"

Tags:

python

string

I'm trying to build a string using ":" and then write that string to a file. Function gets two lists that include strings, which are amounts of money

[["$123,123,123", "$68,656", "$993,993,993,993", "$123,141,142,142"],
 ["$60", "$800,600", "$700,600,500", "$20,200,200,201"]]

It should be written as

"$123,123,123":"$68,656":"$993,993,993,993":"$123,141,142,142"
"$60":"$800,600":"$700,600,500":"$20,200,200,201"

Currently I have something like this:

def save_amount (amount, moneys):
    with open (moneys, "w") as file:
        for i in amount:
            moneys_s = str(i)

How to proceed?

like image 960
SomeBody12345 Avatar asked Mar 28 '26 20:03

SomeBody12345


2 Answers

First flatten the list and then use join, Use list comprehension here :

>>> [ ':'.join('"' + j + '"' for j in i) for i in l ]
['"$123,123,123":"$68,656":"$993,993,993,993":"$123,141,142,142"',
'"$60":"$800,600":"$700,600,500":"$20,200,200,201"']
like image 177
akash karothiya Avatar answered Mar 31 '26 08:03

akash karothiya


'"' + '":"'.join( str(j) for i in money for j in i) + '"'

where money is your list of lists

like image 24
skend Avatar answered Mar 31 '26 08:03

skend



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!