python中如何将函数参数附加到输出列表

2024-04-19 18:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,第一次使用python的函数功能。我写过这样的代码:

def chunks(l, n):
    for i in range(0, len(l), n):
        chunk = l[i:i+n]
        G = chunk.count('G')
        C = chunk.count('C')
        A = chunk.count('A')
        T = chunk.count('T')
        G_C = G+C
        Total_G_C_A_T = G_C+A+T
        G_C_contents = ((G_C) / float(Total_G_C_A_T))*100
        GC_Window100.append(G_C_contents)
    print (GC_Window100)
chunks (list3, 100)
chunks (list3, 150)
chunks (list3, 200)

我的问题是:如何将n的值附加到list中进行计算?就像我使用GC\u Window100一样,我希望100应该来自函数参数,这样我就可以跟踪列表,它来自哪个块。我需要重复这个函数好几次。 我想要的结果是:

GC\u Window100=[30,32,31,42]

GC\u Window150=[18,20,22,20]

GC\u Window200=[15,13,16,10] . . . 你知道吗

有什么帮助吗?提前谢谢。你知道吗


Tags: 函数代码in功能fordefcountcontents
1条回答
网友
1楼 · 发布于 2024-04-19 18:28:59

有几种方法可以做到这一点,但这是一个足够简单的方法。你知道吗

tracked_responses = []
tracked_responses.append(chunks(list3, 100))

然后在chunks函数中,返回如下元组

return (n, CS_Window100)

现在,跟踪的\u响应是一个元组列表,其中输入n作为第一个元素,CS\u Window100值作为第二个元素。你知道吗

此时,将函数变量重命名为CS\u Window而不是CS\u Window100可能是有意义的。你知道吗

你的回答如下:

[(100, [1.2, 1.4, 45.4]), (200, [5.4, 3.4, 1.0]), ...]

如果您需要通过n的值进行访问,那么您可以将这个元组列表强制转换为字典并进行类似的访问。你知道吗

tracked_responses_dict = dict(tracked_responses)
print tracked_responses_dict[100]

因为您是Python新手

下面是一些可以整理代码的方法。你知道吗

  1. 使用收款.计数器你知道吗

你知道吗收款.计数器是一种很好的方法,可以对iterable(如列表)中的唯一项进行分组和分配计数。你知道吗

gcat_counts = collections.counter(chunk)
g_c = gcat_counts.get('G', 0) + gcat_counts.get('C', 0)
a_t = gcat_counts.get('A', 0) + gcat_counts.get('T', 0)

使用get方法将确保获得一些值,即使键不存在。你知道吗

因此修改后的脚本可能如下所示

import collections

def chunks(l, n):
    gc_window = []
    for i in range(0, len(l), n):
        chunk = l[i:i + n]
        gcat_counts = collections.counter(chunk)
        g_c = gcat_counts.get('G', 0) + gcat_counts.get('C', 0)
        a_t = gcat_counts.get('A', 0) + gcat_counts.get('T', 0)
        total_gcat = g_c + a_t
        g_c_contents = (g_c / float(total_gcat)) * 100
        gc_window.append(g_c_contents)
    return (n, gc_window)

tracked_responses = []
tracked_responses.append(chunks(list3, 100))
tracked_responses.append(chunks(list3, 150))
tracked_responses.append(chunks(list3, 200))

tracked_responses_dict = dict(tracked_responses)
print tracked_responses_dict[100]

相关问题 更多 >