如何通过选择元素中字符的唯一组合来过滤列表(Python)?

2024-09-28 22:22:49 发布

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

我在下面的列表中存储了以下几对

 sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,TATA]]

每个成对比较只能有两个唯一的字符组合,如果没有,则消除这些成对比较。例如

   In sample[1]
    C       C
    G       A
    C       T 
    G       C

查看两个子列表中的相应元素,CC、GA、CT、GC。你知道吗

这里,有两种以上的成对(CC),(GA),(CT)和(GC)。所以这种两两比较是不可能发生的。你知道吗

每次比较只能有两种组合(AA、GG、CC、TT、AT、TA、AC、CA、AG、GA、GC、CG、GT、TG、CT、TC)。。。基本上所有可能的ACGT组合,其中顺序很重要。你知道吗

在上面的例子中,发现了超过2个这样的组合。你知道吗

但是

   In sample[0]
    C       A
    G       T
    C       A 
    G       T

只有两种独特的组合:CA和GT

因此,仅存的一对是:

output = [[CGCG,ATAT],[ATAT,TATA]]

我更希望代码是传统的for循环格式,而不是理解

这是所列问题的一小部分here。这部分问题被重新提问,因为前面提供的答案提供了不正确的输出。你知道吗


Tags: sampleingt元素列表字符gcca
3条回答
def filter_sample(sample):
    filtered_sample = []

    for s1, s2 in sample:
        pairs = {pair for pair in zip(s1, s2)}
        if len(pairs) <= 2:
            filtered_sample.append([s1, s2])

    return filtered_sample

运行这个

sample = [["CGCG","ATAT"],["CGCG","CATC"],["ATAT","TATA"]]
filter_sample(sample)

返回此

[['CGCG', 'ATAT'], ['ATAT', 'TATA']]
sample = [[CGCG,ATAT],[CGCG,CATC],[ATAT,CATC]]
result = []
for s in sample:
    first = s[0]
    second = s[1]
    combinations = []
    for i in range(0,len(first)):
        comb = [first[i],second[i]]
        if comb not in combinations:
            combinations.append(comb)
    if len(combinations) == 2:
        result.append(s)

print result

此任务的核心是从子列表中提取对并计算唯一对的数量。假设您的示例实际上包含字符串,您可以使用zip(*sub_list)来获取这些字符串对。然后可以使用set()删除重复的条目。你知道吗

sample = [['CGCG','ATAT'],['CGCG','CATC'],['ATAT','CATC']]

def filter(sub_list, n_pairs):
    pairs = zip(*sub_list)
    return len(set(pairs)) == n_pairs

然后可以使用for循环或列表理解将此函数应用于主列表。你知道吗

new_sample = [sub_list for sub_list in sample if filter(sub_list, 2)]

…或者作为for循环。。。你知道吗

new_sample = []
for sub_list in sample:
    if filter(sub_list, 2):
        new_sample.append(sub_list)

相关问题 更多 >