簡體   English   中英

python 不同數量的鍵字典以指定格式存儲到文本文件

[英]python different number of keys dictionary store to text file in specified format

我有一個字典,格式如下frequent_itemset= {'11': 23, '23': 20, ('20', '32'): 10, ('2', '3'): 9, ('1', '2, '3'): 5} etc. 我想將它存儲在output.txt中,格式如下。

預期結果

11 (23)
23 (20)
20 32 (10)
2 3 (9)
1 2 3 (5)

我寫了這個:

    with open('output.txt', 'w') as file:
        for k, v in frequent_itemset.items():
        file.write("{} ({}) \n".format(" ".join(map(str, k)), v))

結果:

1 1 (23)
1 2 (20)
20 32 (10)
2 3 (9)
1 2 3 (5)

您混淆了 map,因為字符串被認為是可迭代的以及元組/列表。

例如,如果你遍歷一個包含["a", "b", "c"]的列表,你會得到"a", "b", "c" 然而,如果你遍歷一個字符串"abc" ,你也會得到"a", "b", "c"

試試這個...

frequent_itemset= {'11': 23, '23': 20, ('20', '32'): 10, ('2', '3'): 9, ('1', '2', '3'): 5}

for k,v in frequent_itemset.items():
    if isinstance(k, (list, tuple)):
        key = ' '.join([x for x in k])
    else:
        key = k
    print("{} ({})".format(key,v))
frequent_itemset= {'11': 23, '23': 20, ('20', '32'): 10, ('2', '3'): 9, ('1', '2', '3'): 5} 

for k,v in frequent_itemset.items():
    print(*k, '({})'.format(v)) if isinstance(k, tuple) else print(k,'({})'.format(v)) 

output

11 (23)
23 (20)
20 32 (10)
2 3 (9)
1 2 3 (5)

一個簡單for循環:

for x,y in frequent_itemset.items(): print((x if type(x)==str else " ".join(x)) + " (" + str(y) + ")" )

一個班輪:

[print((x if type(x)==str else " ".join(x)) + " (" + str(y) + ")" ) for x,y in frequent_itemset.items()]

結果

11 (23) 23 (20) 20 32 (10) 2 3 (9) 1 2 3 (5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM