我有一個資料集,它是一個 .txt 檔案,每一行都有用空格分隔的專案。每一行都是不同的事務。
資料集如下所示:
資料.txt 檔案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
20 12 5 41 65
41 6 11 27 81 21
65 15 27 8 31 65 20 19 44 29 41
我創建了一個字典,其鍵為序列號。從 0 開始,每行值用逗號分隔,如下所示
{0: '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15', 1:'20,12,5,41,65', 2:'41,6,11,27,81,21', 3: '65,15,27,8,31,65,20,19,44,29,41'}
但我無法遍歷 dict 中的每個值,有什么方法可以將它轉換為每個鍵的值串列
我想在整個字典中找到每次的頻率并創建一個表
| 物品 | 頻率 |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 20 | 2 |
| 41 | 3 |
像上面一樣
my_dict = {}
with open('text.csv', 'r') as file:
lines = file.readlines()
for line in lines:
my_dict[lines.index(line)] = line.strip()
這是我用來創建字典的代碼,但我不確定我應該改變什么,我還需要找到每個值的頻率。
任何幫助,將不勝感激。感謝你。
uj5u.com熱心網友回復:
由于您實際上只是在計算整個檔案的數字,因此您可以:
my_dict = {}
with open('data.txt', 'r') as file:
for number in file.read().split():
my_dict[number] = my_dict.get(number, 0) 1
print(my_dict)
結果:
{'1': 1, '2': 1, '3': 1, '4': 1, '5': 2, '6': 2, '7': 1, '8': 2, '9': 1, '10': 1, '11': 2, '12': 2, '13': 1, '14': 1, '15': 2, '20': 2, '41': 3, '65': 3, '27': 2, '81': 1, '21': 1, '31': 1, '19': 1, '44': 1, '29': 1}
這只是計算代表數字的字串,您可以將它們轉換為實際數字:
with open('data.txt', 'r') as file:
for number in file.read().split():
my_dict[int(number)] = my_dict.get(int(number), 0) 1
結果:
{1: 1, 2: 1, 3: 1, 4: 1, 5: 2, 6: 2, 7: 1, 8: 2, 9: 1, 10: 1, 11: 2, 12: 2, 13: 1, 14: 1, 15: 2, 20: 2, 41: 3, 65: 3, 27: 2, 81: 1, 21: 1, 31: 1, 19: 1, 44: 1, 29: 1}
或者:
my_dict[i] = my_dict.get(i := int(number), 0) 1
uj5u.com熱心網友回復:
另一種解決方案是使用collections.Counter用于計數的:
from collections import Counter
with open("data.txt", "r") as file:
counts = Counter(f.read().split())
如果要將值轉換為整數,
from collections import Counter
with open("data.txt", "r") as file:
counts = Counter(map(int, f.read().split()))
這通過一次將整個檔案讀入一個字串,呼叫str.split()該字串,因為您的資料全部由空格分隔,并將結果串列直接傳遞給Counter().
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532950.html
下一篇:無法使用zip方法替換子字串
