Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取文件并生成已排序的词典_Python_Dictionary - Fatal编程技术网

Python 读取文件并生成已排序的词典

Python 读取文件并生成已排序的词典,python,dictionary,Python,Dictionary,创建包含以下内容的文件: Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5 阅读此文件并创建一个具有tuple类型的键和float类型的值的字典,即字典的一项应如下所示: (‘Mary’,’Jane’) : 5.8 将此词典转换为元组列表。按降序排序并打印 我的代码是: f = open('sam.txt', 'r') answer = {} tuple(answer.keys(

创建包含以下内容的文件:

Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5
阅读此文件并创建一个具有tuple类型的键和float类型的值的字典,即字典的一项应如下所示:

(‘Mary’,’Jane’) : 5.8
将此词典转换为元组列表。按降序排序并打印

我的代码是:

f = open('sam.txt', 'r')
answer = {}
tuple(answer.keys())
for i in answer:
    print tuple(answer.keys())  
for line in f:

    k, v = ((line.strip()).split(':'))
    answer[((k.strip()))] = float(v.strip())
print answer    
c = answer.items()
d = sorted(c)
print tuple(reversed(sorted(c)))
f.close()
在这里,我得到的字典键是字符串而不是规定的元组。请告诉我我的错误,并请对我的问题做一些微调。

您还应该拆分逗号上的键,“”,而不仅仅是条带:

另一方面,您不需要初始dict特技代码:

answer = {}
with open('sam.txt') as f: # open with context manager does auto close
    for line in f:
        k, v = line.strip().split(':')
        answer[tuple(k.strip().split(','))] = float(v.strip())
您还应该拆分逗号
上的键,而不仅仅是条带:

另一方面,您不需要初始dict特技代码:

answer = {}
with open('sam.txt') as f: # open with context manager does auto close
    for line in f:
        k, v = line.strip().split(':')
        answer[tuple(k.strip().split(','))] = float(v.strip())

如果您将数据放在新的行中,则更容易:

Mary,Jane : 5.8 
Mary,Doe : 6.0 
John,Doe : 6.3 
John,Muller : 5.6 
Mary,Muller : 6.5
然后代码是:

f = open('data.txt', 'r')
answer = {}
for line in f:
    k, v = ((line.strip()).split(':'))
    key1, key2 = k.split(',')
    answer[(key1, key2)] = float(v.strip())

print answer
c = answer.items()
d = sorted(c)
print tuple(reversed(sorted(c)))
f.close()

如果您将数据放在新的行中,则更容易:

Mary,Jane : 5.8 
Mary,Doe : 6.0 
John,Doe : 6.3 
John,Muller : 5.6 
Mary,Muller : 6.5
然后代码是:

f = open('data.txt', 'r')
answer = {}
for line in f:
    k, v = ((line.strip()).split(':'))
    key1, key2 = k.split(',')
    answer[(key1, key2)] = float(v.strip())

print answer
c = answer.items()
d = sorted(c)
print tuple(reversed(sorted(c)))
f.close()

我的回答是这样的。我想知道是否需要进一步升级以提高效率

f = open('sam.txt')
answer = {tuple(x.split(':')[0].strip().split(',')): float(x.split('[1].strip()) for x in f}
print "\ndictionary taken from file is:\n"
print answer    
c = answer.items()
d = sorted(c)
print "\nafter sorted and converted into tuples the output is:\n"
print tuple(reversed(sorted(c)))
f.close()

我的回答是这样的。我想知道是否需要进一步升级以提高效率

f = open('sam.txt')
answer = {tuple(x.split(':')[0].strip().split(',')): float(x.split('[1].strip()) for x in f}
print "\ndictionary taken from file is:\n"
print answer    
c = answer.items()
d = sorted(c)
print "\nafter sorted and converted into tuples the output is:\n"
print tuple(reversed(sorted(c)))
f.close()

内置函数通常很有用,但有时只需要一个简单的正则表达式:

# Generate file
txt = "Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5"
with open("out.txt","w+") as FILE: FILE.write(txt)

# Read file and grab content
content= [ re.findall(r"([A-Za-z]+),([A-Za-z]+)\s:\s([0-9]\.[0-9])",line) for line in tuple(open("out.txt","r")) ]

# Make dictionary
dct = {(k1,k2):float(v) for (k1,k2,v) in reduce(lambda x,y: x+y, content)}
print(dct)

内置函数通常很有用,但有时只需要一个简单的正则表达式:

# Generate file
txt = "Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5"
with open("out.txt","w+") as FILE: FILE.write(txt)

# Read file and grab content
content= [ re.findall(r"([A-Za-z]+),([A-Za-z]+)\s:\s([0-9]\.[0-9])",line) for line in tuple(open("out.txt","r")) ]

# Make dictionary
dct = {(k1,k2):float(v) for (k1,k2,v) in reduce(lambda x,y: x+y, content)}
print(dct)

为什么在答案词典明显为空时要对其执行操作?您没有使用
d
,因此需要进行两次排序。顺便说一下,您可以使用
sorted(c,reverse=True)
而不是
reversed(c))
。我被要求使用reversed()函数,所以我尝试这样做。为什么在答案字典明显为空时,您要对其执行操作?您没有使用
d
,因此您要进行两次排序。顺便说一下,您可以使用
sorted(c,reverse=True)
而不是
reversed(sorted(c))
。我被要求使用reversed()函数,所以我尝试这样做