[英]in python, how do you convert a list of strings within a dictionary to a list of integers?
我有一個函數(main),它從 csv 文件中獲取數據並將其轉換為字典,其鍵是第一列中的條目,它們的值是該行中所有其他條目的列表(例如:一行是: 2020-12-20,0,0,0,0,206,
因此鍵是2020-12-20
,其余條目是列表中的字符串: ['0', '0', '0', '0', '206']
):
def main():
import csv
# doses_data_mar_20.csv
dict_doses_by_date = {}
filename_input = str(input("Please enter a .csv file to read: "))
with open(filename_input, "r") as inp, open('doses.csv', 'w') as out:
header = inp.readline()
reader = csv.reader(inp, delimiter=",", quotechar='"')
for line in reader:
dict_doses_by_date[line[0]] = line[1:6]
return dict_doses_by_date
def count_doses_by_date(dict_dose_by_date):
現在我需要定義一個新函數count_doses_by_date
,它將每個字符串列表作為輸入,並將這些字符串列表中的每一個轉換為整數列表,並將所有整數相加以獲得它們的總數。 然后將其輸出到另一個 csv 文件中。
我試過這樣做:
def count_doses_by_date(dict_dose_by_date):
import csv
# doses_data_mar_20.csv
dict_doses_by_date = {}
filename_input = str(input("Please enter a .csv file to read: "))
with open(filename_input, "r") as inp, open('doses.csv', 'w') as out:
header = inp.readline()
reader = csv.reader(inp, delimiter=",", quotechar='"')
for line in reader:
dict_doses_by_date[line[0]] = line[1:6]
for k in dict_doses_by_date:
list_integers = [int(x) for x in dict_doses_by_date[k]]
sum_integers = sum(list_integers)
print_value = "{}, {} \n".format(k, sum_integers)
return out.write(print_value)
但我收到錯誤,因為某些列表包含像 '1,800' 這樣的字符串,其中包含阻止將其轉換為整數的逗號。 我不知道如何在不破壞分隔 csv 值的逗號的情況下擺脫數千個逗號。
我被卡住了..這將如何完成?
因此,如果您的字符串類似於“1234”,您可以這樣做
int(number, base=base)
你會得到一個整數。 例如:
print(int("1234"))
將打印 1234 號碼。
請在此處查看其余文檔: https ://docs.python.org/3/library/functions.html#int
然后要真正實現您想要的,您可以按照其他評論的建議或您想要的任何方式進行操作,只需遍歷元素列表並繼續添加它們 (a+= int("1234")) 然后返回總數並寫入它到文件中。
當然,如果您的字符串有意外的符號,例如“千個逗號”,那么您需要在調用int()
之前通過使用replace()
或其他方式刪除字符來規范化字符串。
你會試試這個嗎? 使用string.isdigit()
判斷是否為數字
line = ['2020-12-20', '0', '0', '0', '0', '206']
filtered_line = [int(e) if e.isdigit() else '' for e in line[1:6]]
print([x for x in filtered_line if x != ''])
輸出
[0, 0, 0, 0, 206]
編輯:我錯過了關於千位分隔符的部分。 在您的用例中,代碼可能是這樣的:
dict_doses_by_date = {}
reader = [['2020-12-20', '0', '0', '0', '10', '206'], ['2020-12-21', '0', '0', '0', '20', '316'], ['2020-12-22', '0', '0', '0', '30', '1,426']]
for line in reader:
list_integers = [int(x.replace(',', '')) for x in line[1:6]]
dict_doses_by_date[line[0]] = list_integers
print_value = "{}, {} \n".format(line[0], sum(list_integers))
print(print_value)
print(dict_doses_by_date)
輸出
2020-12-20, 216
2020-12-21, 336
2020-12-22, 1456
{'2020-12-20': [0, 0, 0, 10, 206], '2020-12-21': [0, 0, 0, 20, 316], '2020-12-22': [0, 0, 0, 30, 1426]}
您應該使用 pandas 庫。 您可以使用pd.read_csv
直接從文件中獲取數據框,並且可以將第一列設置為索引列。 您可以使用df.applymap(lamba x : int(x.replace(',',''))
擺脫逗號並轉換為 int,然后執行df.sum(axis = 1)
以獲得一行-逐行總和。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.