[英]Comparing value in dictionary with list (Python)
我正在處理這個 CS50 問題集,告訴我們匹配人們的 DNA
這是我幾乎完成的代碼:
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
function。 我對如何將我的 dict: str_list
中的值與 list: people
中的值進行比較感到困惑。
str_list = {'AGATC': 4, 'AATG': 1, 'TATC': 5}
data = ['4', '1', '5']
我的代碼有什么我應該改變的嗎? 或者可能是比較這兩種不同結構的簡單方法? 謝謝。
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)
在您提供的第二次剪斷中。 列表數據,即“數據”'4','1','5'在字符串和字典值中,即“str_list”4,1,5在integer形式因此您需要通過轉換來比較相同的數據類型將數據列出到 integer。 您可以查看我上面的代碼供您參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.