修复我的功能的返回格式

问题描述 投票:1回答:2

我的函数的代码正常工作,但它没有以我想要的格式返回函数。该函数计算第二个序列中的种子值,然后将种子计数作为整数列表返回。它返回种子计数但是在单独的行上而不是在列表中。这是我的代码以及它在命令提示符下返回的内容。

    def count_each(seeds,xs):
        for c in seeds:
            count=0
        for d in xs:
            if c==d:
                count=count+1
        print ([count])

count_each([10,20],[10,20,30,10])

count_each([4,8],[1,2,4,4,4,8,8,10])

在命令提示符下,我希望这个函数为count_each([10,20],[10,20,30,10])和[3,2]打印[2,1]为count_each([4,8], [1,2,4,4,4,8,8,10])但是它会像这样在自己的行上打印每个种子值

http://i.stack.imgur.com/vXAd3.png

在上面的图片中,它在单独的行上打印[2],[1],[3]和[2],而它应该为两个序列打印两行[2,1]和[3,2]。如何让函数将每个序列的种子值作为列表返回,而不是将值放在单独的行上。

编辑:我需要完成此操作而无需从其他模块导入并使用最简单的代码。

python list format sequence
2个回答
2
投票

你差不多完成了,但如果你想在列表中打印输出,你必须先创建一个列表。在这里,试试这个:

def count_each(seeds,xs):
    output = []
    for c in seeds:
        count=0
        for d in xs:
            if c==d:
                count=count+1
        output.append(count)
    print (output)

0
投票

我认为你的代码不起作用。试试这个:

def count_each(seeds,xs):
    from collections import Counter
    counter_dict = dict(Counter(xs))
    count = []
    for s in seeds:
        count.append(counter_dict[s])
    print count

if __name__ == "__main__":
    count_each([10,20],[10,20,30,10])
    count_each([4,8],[1,2,4,4,4,8,8,10])

基本上,Counter为您提供列表中每个唯一元素的计数。

Update:

刚刚为Python的count找到了list方法。代码如下:

def count_each(seeds,xs):
    from collections import Counter
    count = []
    for s in seeds:
        count.append(xs.count(s))
    print count
© www.soinside.com 2019 - 2024. All rights reserved.