猿问

将列表与字典进行比较并生成新列表。新列表的长度是 1?

我正在尝试通过将列表A中的元素与字典中的X元素进行比较来生成列表B。列表 B 应从字典中生成 X 和列表 A 匹配的所有 Y 元素。


这是我的列表和字典(这是DNA翻译成蛋白质的程序):


这是我的代码:


protlist = []

for i in range(0,Len): # Len is length of tuple

    tu = tuple[3*i:3*i+3]


    if tu in diction:

        for x,y in diction.items():

            if tu == x:

                protlist = [y]

                print(*protlist,end =" ") # This prints each y value in a linear fashion

                break

print(len(protlist))  


这是我的预期输出:


此代码将表面上生成正确的列表。但是,当我调用列表的长度时,它输出为1。我尝试用保护列表替换保护列表 = [y]。这给出了列表的正确长度和错误的输出。


我还尝试使用连接函数而不是''.join(y),但这也给出了不正确的列表长度。


如何编辑代码以实现正确的输出和列表长度?谢谢。


达令说
浏览 119回答 1
1回答

吃鸡游戏

您得到是因为您为 中的每个循环重新分配了单个值。然后,替换 会给出错误的输出,因为您在每个循环中打印。len(protlist) = 1protlistfor x,y in diction.items()protlist = [y]protlist.append(y)protlist但是,要开始,不应是 的长度。元组的长度是 ,但每个循环中有三个字符,然后转到接下来的三个字符。因此,您需要迭代才能到达字符串的末尾。Lentuple1170tu1170 / 3 = 390然后有很多方法可以解决您的问题。像您提到的具有列表和联接的示例是在循环中附加值,然后在循环外部进行打印和计数。protlist = []for i in range(0, int(len(tuple) / 3)):    tu = tuple[3*i:3*i+3]    if tu in diction:        for x, y in diction.items():            if tu == x:                protlist.append(y)                breakprint(' '.join(protlist)) #prints list items separated by a spaceprint(len(protlist))我根据你的预期输出进行了测试,它给了我确切的结果。编辑:此问题的类似简化版本的列表理解示例:string = 'aaabbbcccdddeee'dictionary = {'aaa': 'A', 'bbb': 'B', 'ccc': 'C', 'ddd': 'D', 'eee': 'E'}parts = [ string[i:i+3] for i in range(0, len(string), 3) ]output = [ dictionary[x] for x in parts if x in dictionary.keys() ]print(' '.join(output))
随时随地看视频慕课网APP

相关分类

Python
我要回答