例如,如果我有一个基因名称列表,并且我想创建一个仅包含重复基因的新列表,我该怎么做?
原始列表示例:
RGN
RBM10
ARAF
ZNF630
FTSJ1
SLC35A2
SLC35A2
SLC35A2
MAGIX
DGKK
XAGE1B
XAGE1B
SMC1A
FAM120C
CXorf49
CXorf49B
CHIC1
ABCB7
PBDC1
FGF16
ATP7A
CYLC1
TSPAN6
BTK
BTK
TCEAL4
TEX13A
FRMPD3
PRPS1
COL4A6
COL4A6
COL4A6
例如,SLC35A2
将出现在新列表中,因为它会重复3次。
请提出建议。
答案 0 :(得分:4)
collections.Counter
使操作变得快速而简单:
from collections import Counter
# Using other answer's listOfGenes for convenience
listOfGenes = "RGN RBM10 ARAF ZNF630 FTSJ1 SLC35A2 SLC35A2 SLC35A2 MAGIX DGKK XAGE1B XAGE1B SMC1A FAM120C CXorf49 CXorf49B CHIC1 ABCB7 PBDC1 FGF16 ATP7A CYLC1 TSPAN6 BTK BTK TCEAL4 TEX13A FRMPD3 PRPS1 COL4A6 COL4A6 COL4A6".split()
# Actual work is a one-liner; count them all, keep those with count of 2 or more
duplicates = [gene for gene, cnt in Counter(listOfGenes).items() if cnt >= 2]
在CPython 3.6和更高版本(以及到达3.7的所有Python解释器)上,提供插入顺序为dict
的{{1}} duplicates
将按照在{{ 1}};在3.5及更早版本上,它将具有任意顺序。
答案 1 :(得分:1)
您可以这样做:
listOfGenes = "RGN RBM10 ARAF ZNF630 FTSJ1 SLC35A2 SLC35A2 SLC35A2 MAGIX DGKK XAGE1B XAGE1B SMC1A FAM120C CXorf49 CXorf49B CHIC1 ABCB7 PBDC1 FGF16 ATP7A CYLC1 TSPAN6 BTK BTK TCEAL4 TEX13A FRMPD3 PRPS1 COL4A6 COL4A6 COL4A6".split(" ")
genesOccurences = {}
for gene in listOfGenes:
occurence = genesOccurences.get(gene, 0)
genesOccurences[gene] = occurence + 1
print(genesOccurences) # will print a dictionary with every gene and how often it is occurring
filteredGeneList = [ key for key in genesOccurences if genesOccurences[key] > 1 ]
print(filteredGeneList) # will print only those genes occurring > 1 times.
答案 2 :(得分:1)
O(n)
O(n)
代码:
def get_duplicates(array):
seen = set([])
results = set([])
for element in array:
if element in seen:
results.add(element)
else:
seen.add(element)
return list(results)
input_array = "RGN RBM10 ARAF ZNF630 FTSJ1 SLC35A2 SLC35A2 SLC35A2 MAGIX DGKK XAGE1B XAGE1B SMC1A FAM120C CXorf49 CXorf49B CHIC1 ABCB7 PBDC1 FGF16 ATP7A CYLC1 TSPAN6 BTK BTK TCEAL4 TEX13A FRMPD3 PRPS1 COL4A6 COL4A6 COL4A6"
input_array = input_array.split()
duplicates = get_duplicates(input_array)
print(duplicates)
输出:
['COL4A6', 'SLC35A2', 'XAGE1B', 'BTK']