我對python和編碼很陌生。我正在嘗試撰寫一個代碼,該代碼將從電線串列中列印出每種給定電線型別的總量。這是一個作業的副業。我能夠想出一個代碼來總結用戶定義的電線型別的所有電線。現在我想制作另一個代碼來列印檔案中每種電線型別的總數。
這是我想出的代碼,用于總結用戶選擇的單個電線型別。
wtype = []
w = []
w1 = []
#opens the .TXT file
fhand = input('\nEnter Text File\n')
try:
if (len(fhand) <= 0):
fhand = 'test.txt'
fh = open(fhand)
except:
print('\nNo File Found:', fhand, '\n')
exit()
#prints out the possible wire types
for line in fh:
line = line.rstrip()
wtype.append(line) #needed for later in the code
line2 = line.split(',')[2]
if line2 not in w:
w.append(line2)
else:
continue
d1 = dict(enumerate(w))
print(d1)
#sums up the selected wire types total length from the given .TXT file
wire = int(input('\nEnter the number that is before the wire type you need:\n'))
for key, val in d1.items():
if key == wire:
for x in wtype:
x = x.split(',')
if x[2] == val:
w1.append(x[1])
else:
continue
s = [eval(i) for i in w1]
print('\nYour will need ', sum(s)/12, ' Feet of ', val, '.\n')
這是test.txt檔案,長度以英寸為單位,在代碼的最后一行轉換為英尺sum(s)/12:
該檔案的列是 WIRE、LENGTH、TYPE、QTY。
WIRE-006A22,72,M22759/16-22-9,1
WIRE-005A22,60,M22759/16-22-9,1
WIRE-004A22,72,M22759/16-22-9,1
WIRE-003A22,72,M22759/16-20-9,1
WIRE-002A22,60,M22759/16-20-9,1
WIRE-001A22,72,M22759/16-22-9,1
WIRE-009A22,72,M22759/16-22-9,1
WIRE-008A22,60,M22759/16-22-9,1
WIRE-007A22,72,M22759/16-20-9,1
WIRE-011A22,72,M22759/16-22-9,1
WIRE-012A22,72,M22759/16-22-9,1
WIRE-014A22,72,M22759/16-20-9,1
WIRE-013A22,60,M22759/16-22-9,1
WIRE-021A22,72,M22759/16-20-9,1
WIRE-031A22,72,M22759/16-22-9,1
WIRE-032A22,72,M22759/16-20-9,1
WIRE-043A22,60,M22759/16-22-9,1
WIRE-054A22,72,M22759/16-20-9,1
WIRE-065A22,72,M22759/16-22-9,1
WIRE-076A22,60,M22759/16-22-9,1
WIRE-087A22,72,M22759/16-22-9,1
WIRE-098A22,72,M22759/16-20-9,1
WIRE-089A22,72,M22759/16-20-9,1
WIRE-078A22,72,M22759/16-20-9,1
WIRE-067A22,60,M22759/16-22-9,1
WIRE-056A22,72,M22759/16-22-9,1
WIRE-045A22,72,M22759/16-20-9,1
WIRE-034A22,60,M22759/16-22-9,1
WIRE-023A22,60,M22759/16-22-9,1
WIRE-012A22,72,M22759/16-20-9,1
我希望嘗試實作的輸出是:
output: {'M22759/16-22-9': 100, 'M22759/16-20-9': 71}
并使其可擴展到可能存在的所有不同電線型別 d1
uj5u.com熱心網友回復:
與您所做的類似 - 但在迭代時制作字典后會遍歷整個檔案。
import collections
d = collections.defaultdict(int)
with open('thefile.txt') as f:
next(f)
for line in f:
wire,length,type,qty = line.strip().split(',')
d[type] = int(length)
for type,l in d.items():
print(type,l)
>>>
M22759/16-22-9 1200
M22759/16-20-9 852
對于英尺而不是英寸:
import collections
d = collections.defaultdict(float)
with open('thefile.txt') as f:
next(f)
for line in f:
wire,length,type,qty = line.strip().split(',')
d[type] = int(length)/12
uj5u.com熱心網友回復:
這是一種使用 pandas 庫的簡單方法,只需很少的代碼。
import pandas
df = pandas.read_csv("test.csv")
df_out = df.groupby("TYPE")["QTY"].sum()
print("Output:", df_out.to_dict())
# Output: {'M22759/16-20-9': 12, 'M22759/16-22-9': 18}
它假定輸入 CSV 檔案如下所示:
WIRE,LENGTH,TYPE,QTY
WIRE-006A22,72,M22759/16-22-9,1
WIRE-005A22,60,M22759/16-22-9,1
WIRE-004A22,72,M22759/16-22-9,1
WIRE-003A22,72,M22759/16-20-9,1
...
如果 CSV 檔案沒有標題,那么您仍然可以使用 pandas。告訴它沒有標題,然后使用列號而不是列名。例如:
import pandas
df = pandas.read_csv("test-noheader.csv", header=None)
df_out = df.groupby(2)[3].sum()
print("Output:", df_out.to_dict())
當然,您可以使用非熊貓代碼相當簡單地獲得相同的結果,但我認為值得分享這可能是幾行代碼。
這是一個使用標準 csv 模塊的簡單非熊貓版本:
import csv
output = {}
with open("test.csv") as csvfile:
for row in csv.DictReader(csvfile):
if row["TYPE"] in output:
output[row["TYPE"]] = int(row["QTY"])
else:
output[row["TYPE"]] = int(row["QTY"])
print("Output:", output)
同樣,如果 CSV 檔案沒有標題:
import csv
output = {}
with open("test-noheader.csv") as csvfile:
for row in csv.DictReader(csvfile, fieldnames=["WIRE", "LENGTH", "TYPE", "QTY"]):
if row["TYPE"] in output:
output[row["TYPE"]] = int(row["QTY"])
else:
output[row["TYPE"]] = int(row["QTY"])
print("Output:", output)
PS您的文本檔案實際上是一個csv檔案,因此最好相應地命名它(例如test.csv)。
uj5u.com熱心網友回復:
我建議使用 csv 檔案,以便您可以正確地對資料進行排序。我有一些東西可以幫助您入門。它不包括您的輸入選項,但希望這對您有用。我有一些 Python 經驗,但按照我的標準 #It 顯示仍然被認為是初學者。:)
import pandas as py
data = py.read_csv('testfile.csv').sort_values(by=['col3'])
wtype = []
w = []
w1 = []
data_dict = {}
this_val = ''
for x in data.iterrows():
wire_name = x[1][2]
if this_val == wire_name:
data_dict[wire_name] = x[1][1]
else:
data_dict[wire_name] = x[1][1]
this_val = wire_name
#Removed to use dict comp
data_dict = {key:int(val/12) for key,val in data_dict.items()}
#for key,val in data_dict.items():
#data_dict[key] = int(val/12)
print(data_dict)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/522049.html
標籤:Python字典
