我有一个包含两列的文件,如下所示
-34G trendmar
+41G trendmar
1.4G ttpsenet
3.6G tyibahco
-13M uberhelp
+19M uberhelp
-8.9G umljgate
+9.2G umljgate
我想将它存储在字典中以进行一些数学运算,但是使用第一列作为值,第二列作为键。
我怎么能这样做?
答案 0 :(得分:4)
您可以逐行读取文件,在空格上拆分并反向使用元素来创建字典:
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
本质上是一个哈希映射,因此它不能有重复的密钥 - 如果重复密钥的值出现在文件中,它们将被最新值覆盖。
更新:如果您想保留所有值,您必须将它们存储为列表,例如:
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
现在你的data
看起来像是:
{'trendmar': ['-34G', '+41G'], 'ttpsenet': ['1.4G'], 'tyibahco': ['3.6G'],
'uberhelp': ['-13M', '+19M'], 'umljgate': ['-8.9G', '+9.2G']}
更新2:如果您想总结,而不是你&#39的值;会首先需要把它们转换成浮筒,然后用普通的算术运算,以达到最终值,所以先写一个函数将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
现在,您可以在创建list
时将float
替换为data
并将值相加而不是追加:
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'}
答案 1 :(得分:2)
with open("file.txt","r") as file:
print({e.split(" ")[1]:e.split(" ")[0] for e in file})
您可以使用词典理解
答案 2 :(得分:1)
假设您希望将更多值与您的计算关键字相关联,这就是我的方法:
d = {}
with open("input.txt") as infile:
lines = infile.readlines()
keys = sorted(set(line.split()[1] for line in lines))
for key in keys:
tempList = []
for line in lines:
if line.split()[1]==key:
tempList.append(line.split()[0])
d.update({key:tempList})
print(d)
输出:
{'trendmar': ['-34G', '+41G'], 'uberhelp': ['-13M', '+19M'], 'umljgate': ['-8.9G', '+9.2G'], 'ttpsenet': ['1.4G'], 'tyibahco': ['3.6G']}
修改强>
如果您希望找到两个值之间的差异,可以使用literal_eval
模块中的ast
函数执行此操作,如下所示:
from ast import literal_eval
d = {'trendmar': ['-34G', '+41G'], 'uberhelp': ['-13M', '+19M'], 'umljgate': ['-8.9G', '+9.2G'], 'ttpsenet': ['1.4G'], 'tyibahco': ['3.6G']}
first = 0
second = 1
diff = []
for key in d.keys():
if len(d[key])==2:
diff.append(key + " : " + str(literal_eval("".join([d[key][first][:-1] ," - (", d[key][second][:-1], ")"]))) + d[key][first][-1])
else:
diff.append(key + " : " + str(literal_eval(str(d[key][0][:-1]))) + d[key][0][-1])
print(diff)
输出:
['uberhelp : -32M', 'tyibahco : 3.6G', 'ttpsenet : 1.4G', 'umljgate : -18.1G', 'trendmar : -75G']
在上面的例子中,我们从第二个值中减去第一个值。如果您希望相反,则交换first
和second
的值。