python-list与set相互转换时的一个注意事项

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/lyc0424/article/details/102770230

首先以一个题目为例,题目名为 5-血型遗传检测 (此处代码用的是python2):

题目描述

血型遗传对照表如下:

父母血型 子女会出现的血型 子女不会出现的血型
O与O O A,B,AB
A与O A,O B,AB
A与A A,O B,AB
A与B A,B,AB,O ——
A与AB A,B,AB O
B与O B,O A,AB
B与B B,O A,AB
B与AB A,B,AB O
AB与O A,B O,AB
AB与AB A,B,AB O

请实现一个程序,输入父母血型,判断孩子可能的血型。

给定两个字符串fathermother,代表父母的血型,请返回一个字符串数组,代表孩子的可能血型(按照字典序排列)。

测试样例:

”A”,”A”
返回:[”A”,“O”]

一开始的代码如下:

# -*- coding:utf-8 -*-

class ChkBloodType:
    def chkBlood(self, father, mother):
        if father=='AB' or mother=='AB':
            if father=='O' or mother=='O':
                return ['A','B']
            else:
                return ['A','AB','B']
        elif father==mother:
            if father!='O':
                return list(set([father,mother,'O']))
            else:
                return ['O']
        elif father=='O' or mother=='O':
            return [father,mother]
        else:
            return ['A','AB','B','O']

结果:

然后我再改动一下代码:

# -*- coding:utf-8 -*-

class ChkBloodType:
    def chkBlood(self, father, mother):
        if father=='AB' or mother=='AB':
            if father=='O' or mother=='O':
                return ['A','B']
            else:
                return ['A','AB','B']
        elif father==mother:
            if father!='O':
                return list(set([father,mother,'O']))
            else:
                return ['O']
        elif father=='O' or mother=='O':
            return list(set([father,mother]))
        else:
            return ['A','AB','B','O']

 结果通过了

当然你可以直接用list的排序方法sort(),结果也是一样正确

切记不能直接return tmp.sort()或return [father,mother].sort(),不要多问(因为试过。。。),其实是因为sort()该方法没有返回值,但是会对列表的对象进行排序。

好了,回到正题,此时是set转list,细心的同学通过两次代码的结果可以发现像上面那样转换的时候居然自动排序了,连sort()都没用!

相关的博客还可以参考这篇https://blog.csdn.net/daigualu/article/details/73928723

接下来是list转set了,方法如下:

多提一下,上面那道题还可以像下面那样解:

# -*- coding:utf-8 -*-

class ChkBloodType:
    def chkBlood(self, father, mother):
        merge=[father,mother]
        if 'AB' in merge:
            if 'O' in merge:
                return ['A','B']
            else:
                return ['A','AB','B']
        elif father==mother:
            if 'O' in merge:
                return ['O']
            else:
                return list(set(merge+['O']))
        elif 'O' in merge:
            merge.sort()
            return merge
        else:
            return ['A','AB','B','O']

猜你喜欢

转载自blog.csdn.net/lyc0424/article/details/102770230