【问题标题】:Comparing value in dictionary with list (Python)将字典中的值与列表进行比较(Python)
【发布时间】:2021-02-12 12:31:03
【问题描述】:

我正在处理这个告诉我们匹配人 DNA 的 CS50 问题集

这是我几乎完成的代码:

import re, csv, sys

def main(argv):

    # Open csv file
    csv_file = open(sys.argv[1], 'r')
    people = csv.reader(csv_file)

    nucleotide = next(people)[1:]

    # Open dna sequences file
    txt_file = open(sys.argv[2], 'r')
    dna_file = txt_file.read()

    str_repeat = {}
    str_list = find_STRrepeats(str_repeat, nucleotide, dna_file)
    
    match_dna(people, str_list)


def find_STRrepeats(str_list, nucleotide, dna):
    for STR in nucleotide:
        groups = re.findall(rf'(?:{STR})+', dna)
        if len(groups) == 0:
            str_list[STR] = 0
        else:
            total = max(len(i)/len(STR) for i in groups)
            str_list[STR] = int(total)
        
    return str_list


def match_dna(people, str_list):
    for row in people:
        # Get people name in people csv
        person = row[0]
        # Get all dna value of each people
        data = row[1:]
        
        # If all value in dict equal with all value in data, print the person
        if str_list.values() == data:
           print(person)
           sys.exit(0)
    
    print("No match")

if __name__ == "__main__":
   main(sys.argv[1:])

所以,我坚持使用 match_dna 功能。我对如何比较字典中的值:str_list 与列表中的值:people 感到困惑。

str_list = {'AGATC': 4, 'AATG': 1, 'TATC': 5}

data = ['4', '1', '5']

我的代码有什么需要改变的吗?或者可能是比较这两种不同结构的简单方法?谢谢。

【问题讨论】:

  • 您可以使用== 来比较str_listdata,就像您已经在做的那样。无论如何,您应该确保两个列表中字段的顺序相同,即确保您没有将 AGATC 值与 TATC 值进行比较。
  • Python 支持列表的结构相等性。但是,数据成员的类型和 str_list 的值类型是不同的。另外,在顺序上不能依赖str_list.values()的返回,所以最好在比较之前对两个列表(data和str_list.values())进行排序。
  • 我猜 CSV 文件按给定顺序存储值。我会为str_list 使用OrderedDict,以确保我以相同的顺序将值存储在字典中。然后你可以安全地进行str_list.values() == data 比较。
  • data=row[1:],评论说“获取每个人的所有 dna 值”根据您的流程是正确的。
  • @rturrado 它不起作用,它总是打印不匹配。我在哪里把OrderedDict 放在我的代码中?

标签: python dictionary cs50


【解决方案1】:
str_list = {'AGATC': 4, 'AATG': 1, 'TATC': 5}

data = ['4', '1', '5']

for data_item in data:

    for key,values in str_list.items():
    
        # list data '4','1','5' are in string 
        # and dictonery value 4,1,5 are in integer form
        # hence you need to compare the same data type 
    
        if values == int(data_item):
            print(key)

在您提供的第二个片段中。列表数据,即“data”'4','1','5'在字符串中,字典值,即“str_list”4,1,5是整数形式,因此您需要通过转换来比较相同的数据类型将数据列表为整数。以上代码可以通过我查看,供您参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多