将子列表与":"

时间:2017-07-28 10:58:57

标签: python string

我尝试使用"来构建字符串:"然后将该字符串写入文件。 函数获取两个包含字符串的列表,这些字符串是金钱

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

应该写成

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

目前我有这样的事情:

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

如何进行?

3 个答案:

答案 0 :(得分:2)

首先展平列表,然后使用join,在此使用列表推导:

>>> [ ':'.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"']

答案 1 :(得分:1)

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

钱是您的清单列表

答案 2 :(得分:1)

l = [["$123,123,123", "$68,656", "$993,993,993,993", "$123,141,142,142"],
     ["$60", "$800,600", "$700,600,500", "$20,200,200,201"]]
[ ':'.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"']