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)
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'}
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
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
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)
你可以用字典来理解
假设您希望在计算时将更多值与键相关联,我的方法是:
输出:
编辑:
如果您希望找到两个值之间的差异,可以使用
literal_eval
模块中的ast
函数来完成,如下所示:输出:
在上面的例子中,我们从第二个值中减去第一个值。如果希望相反,则交换
first
和second
的值。你知道吗您可以逐行读取文件,按空格拆分,并反向使用元素来创建字典:
注意
dict
本质上是一个散列映射,因此它不能有重复的键-如果重复键的值出现在文件中,它们将被最新的值覆盖。你知道吗更新:如果要保留所有值,必须将它们存储为列表,例如:
现在你的
data
看起来像:更新2:如果要对值求和,则首先需要将它们转换为浮点值,然后使用常规算术运算来获得最终值,因此首先编写一个函数,将SI速记符号转换为本机
float
:现在您可以在创建
data
时用list
替换float
,并对值求和,而不是追加:这将导致
data
如下:如果要将这些值返回到SI缩写符号中,则必须编写
si_to_float()
的相反函数,然后使用它转换所有data
值,即:这将最终导致
data
包含:你可以用字典来理解
相关问题 更多 >
编程相关推荐