我面临着这个问题。我的字典中有10,000行,这是其中一行
示例:A(8)C(4)G(48419)T(2)打印出来时
我想把'G'作为答案,因为它具有最高价值。
我目前正在使用Python 2.4,我不知道如何解决这个问题,因为我是Python的新手。
非常感谢您给予的任何帮助:)
答案 0 :(得分:3)
这是
的解决方案我还添加了一个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 "%s\n" % 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"))
答案 1 :(得分:1)
max(d.itervalues())
这比d.values()要快得多,因为它使用的是可迭代的。
答案 2 :(得分:1)
尝试以下方法:
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.
答案 3 :(得分:0)
使用正则表达式分割线条。然后对于所有匹配的组,您必须将匹配的字符串转换为数字,获取最大值,并找出相应的字母。
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
答案 4 :(得分:0)
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'