我有一个包含两列的文件,如下所示
-34G trendmar
+41G trendmar
1.4G ttpsenet
3.6G tyibahco
-13M uberhelp
+19M uberhelp
-8.9G umljgate
+9.2G umljgate
我想将它存储在字典中以进行一些数学运算,但使用第一列作为值,第二列作为键。
我该怎么做?
请您参考如下方法:
您可以逐行读取您的文件,在空格处拆分并反向使用元素来创建字典:
with open("your_file", "r") as f: # open the file for reading
# read it line by line, split and invert the fields to use as k:v for your dict
data = dict(reversed(line.split()) for line in f)
# {'trendmar': '+41G', 'ttpsenet': '1.4G', 'tyibahco': '3.6G',
# 'uberhelp': '+19M', 'umljgate': '+9.2G'}
请注意 dict 本质上是一个 HashMap ,因此它不能有重复的键 - 如果重复键的值出现在文件中,它们将被最新的值覆盖。
更新:如果您想保留所有值,您必须将它们存储为列表,例如:
import collections
data = collections.defaultdict(list) # initiate all fields as lists
with open("your_file", "r") as f: # open the file for reading
for line in f: # read the file line by line
value, key = line.split() # split the line to value and key
data[key].append(value) # append the value to the list for its key
现在您的数据将如下所示:
{'trendmar': ['-34G', '+41G'], 'ttpsenet': ['1.4G'], 'tyibahco': ['3.6G'],
'uberhelp': ['-13M', '+19M'], 'umljgate': ['-8.9G', '+9.2G']}
更新 2: 如果您想对值求和,您首先需要将它们转换为 float ,然后使用常规算术运算得出最终值,因此首先编写一个函数来转换从 SI 速记符号到原生 float:
QUANTIFIER_MAP = {"p": 1e15, "t": 1e12, "g": 1e9, "m": 1e6, "k": 1e3}
def si_to_float(number):
try:
last_char = number[-1].lower()
if last_char in QUANTIFIER_MAP:
return float(number[:-1]) * QUANTIFIER_MAP[last_char]
return float(number)
except ValueError:
return 0.0
现在您可以在创建 data 时将 list 替换为 float 并对值求和而不是追加:
import collections
data = collections.defaultdict(float) # initiate all fields as integers
with open("your_file", "r") as f: # open the file for reading
# read it line by line, split and invert the fields to use as k:v for your dict
for line in f: # read the file line by line
value, key = line.split() # split the line to value and key
data[key] += si_to_float(value) # convert to float and add to the value for this key
这将导致 data 为:
{'trendmar': 7000000000.0, 'ttpsenet': 1400000000.0, 'tyibahco': 3600000000.0,
'uberhelp': 6000000.0, 'umljgate': 300000000.0}
如果您想将这些值返回为 SI 缩写符号,则必须编写 si_to_float() 的相反函数,然后转换您所有的data 使用它的值,即:
QUANTIFIER_STACK = ((1e15, "p"), (1e12, "t"), (1e9, "g"), (1e6, "m"), (1e3, "k"))
def float_to_si(number):
for q in QUANTIFIER_STACK:
if number >= q[0]:
return "{:.1f}".format(number / q[0]).rstrip("0").rstrip(".") + q[1].upper()
return "{:.1f}".format(number).rstrip("0").rstrip(".")
# now lets traverse the previously created 'data' and convert its values:
for k, v in data.items():
data[k] = float_to_si(v)
最后,这将导致 data 包含:
{'trendmar': '7G', 'ttpsenet': '1.4G', 'tyibahco': '3.6G',
'uberhelp': '6M', 'umljgate': '300M'}
