从字典中获取最大值

我面临着这个问题。我的字典中有10,000行,这是其中一行 示例:A(8)C(4)G(48419)T(2)打印输出时 我想把'G'作为答案,因为它具有最高价值。 我目前正在使用Python 2.4,我不知道如何解决这个问题,因为我是Python的新手。 非常感谢任何给予的帮助:)     
已邀请:
这是一个解决方案 使用正则表达式扫描所有出现的大写字母,后跟括号中的数字 将带有生成器表达式的regexp中的字符串对转换为(value,key)元组 从具有最高值的元组返回键 我还添加了一个main函数,以便脚本可以用作命令行工具来读取一个文件中的所有行,并将每行最高值的键写入输出文件。该程序使用迭代器,因此无论输入文件有多大,它都具有内存效率。
import re
KEYVAL = re.compile(r"([A-Z])s*((d+))")

def max_item(row):
    return max((int(v),k) for k,v in KEYVAL.findall(row))[1]

def max_item_lines(fh):
    for row in fh:
        yield "%sn" % max_item(row)

def process_file(infilename, outfilename):
    infile = open(infilename)
    max_items = max_item_lines(infile)
    outfile = open(outfilename, "w")
    outfile.writelines(max_items)
    outfile.close()

if __name__ == '__main__':
    import sys
    infilename, outfilename = sys.argv[1:]
    process_file(infilename, outfilename)
对于单行,您可以致电:
>>> max_item("A (8) C (4) G (48419) T (2)")
'G'
并处理完整的文件:
>>> process_file("inputfile.txt", "outputfile.txt")
如果你想要一个每行最大值的实际Python列表,那么你可以使用:
>>> map(max_item, open("inputfile.txt"))
    
max(d.itervalues())
这比d.values()要快得多,因为它使用的是iterable。     
请尝试以下方法:
st = "A (8) C (4) G (48419) T (2)" # your start string
a=st.split(")")
b=[x.replace("(","").strip() for x in a if x!=""]
c=[x.split(" ") for x in b]
d=[(int(x[1]),x[0]) for x in c]
max(d) # this is your result.
    
使用正则表达式来分割线条。然后,对于所有匹配的组,您必须将匹配的字符串转换为数字,获取最大值,并找出相应的字母。
import re
r = re.compile('A ((d+)) C ((d+)) G ((d+)) T ((d+))')
for line in my_file:
  m = r.match(line)
  if not m:
    continue # or complain about invalid line
  value, n = max((int(value), n) for (n, value) in enumerate(m.groups()))
  print "ACGT"[n], value
    
row = "A (8) C (4) G (48419) T (2)"

lst = row.replace("(",'').replace(")",'').split() # ['A', '8', 'C', '4', 'G', '48419', 'T', '2']

dd = dict(zip(lst[0::2],map(int,lst[1::2]))) # {'A': 8, 'C': 4, 'T': 2, 'G': 48419} 

max(map(lambda k:[dd[k],k], dd))[1] # 'G'
    

要回复问题请先登录注册