我有一个像这样的小例子的列表清单:
[['chr19', '35789598', '35789629', '21', 'chr19', '35510000', '36200000'], ['chr19', '35789598', '35789629', '24', 'chr19', '35510000', '36200000'], ['chr19', '35789598', '35789629', '52', 'chr19', '35510000', '36200000'], ['chr19', '35789598', '35789629', '88', 'chr19', '35510000', '36200000'], ['chr19', '35798974', '35799005', '56', 'chr19', '35510000', '36200000'], ['chr19', '35883830', '35883861', '16', 'chr19', '35510000', '36200000'], ['chr19', '35884320', '35884351', '51', 'chr19', '35510000', '36200000']]
如您所见,每个内部列表都有7个元素。我要创建一个新的列表列表,其中没有内部列表具有相似的第一,第二和第三元素。实际上,如果有一些内部列表,其中第1个,第2个和第3个元素是相似的,那么我将仅获取第一个内部列表,然后删除其他内部列表。小示例的预期输出如下所示:
预期输出:
[['chr19', '35789598', '35789629', '21', 'chr19', '35510000', '36200000'], ['chr19', '35798974', '35799005', '56', 'chr19', '35510000', '36200000'], ['chr19', '35883830', '35883861', '16', 'chr19', '35510000', '36200000'], ['chr19', '35884320', '35884351', '51', 'chr19', '35510000', '36200000']]
这是python中的代码,不会返回我期望的值:
result = []
for i in mat:
for j in i:
if j == j-1:
result.append(j)
答案 0 :(得分:1)
我会用熊猫:
import pandas as pd
data = [['chr19', '35789598', '35789629', '21', 'chr19', '35510000', '36200000'],
['chr19', '35789598', '35789629', '24', 'chr19', '35510000', '36200000'],
['chr19', '35789598', '35789629', '52', 'chr19', '35510000', '36200000'],
['chr19', '35789598', '35789629', '88', 'chr19', '35510000', '36200000'],
['chr19', '35798974', '35799005', '56', 'chr19', '35510000', '36200000'],
['chr19', '35883830', '35883861', '16', 'chr19', '35510000', '36200000'],
['chr19', '35884320', '35884351', '51', 'chr19', '35510000', '36200000']]
# Convert your list of list to a DataFrame
df = pd.DataFrame(data)
0 1 2 3 4 5 6
0 chr19 35789598 35789629 21 chr19 35510000 36200000
1 chr19 35789598 35789629 24 chr19 35510000 36200000
2 chr19 35789598 35789629 52 chr19 35510000 36200000
3 chr19 35789598 35789629 88 chr19 35510000 36200000
4 chr19 35798974 35799005 56 chr19 35510000 36200000
5 chr19 35883830 35883861 16 chr19 35510000 36200000
6 chr19 35884320 35884351 51 chr19 35510000 36200000
df = df.drop_duplicates([0, 1, 2], keep='first')
0 1 2 3 4 5 6
0 chr19 35789598 35789629 21 chr19 35510000 36200000
4 chr19 35798974 35799005 56 chr19 35510000 36200000
5 chr19 35883830 35883861 16 chr19 35510000 36200000
6 chr19 35884320 35884351 51 chr19 35510000 36200000
# If you need the data as the list of lists still output like this:
output = df.values
array([['chr19', '35789598', '35789629', '21', 'chr19', '35510000', '36200000'],
['chr19', '35798974', '35799005', '56', 'chr19', '35510000', '36200000'],
['chr19', '35883830', '35883861', '16', 'chr19', '35510000', '36200000'],
['chr19', '35884320', '35884351', '51', 'chr19', '35510000', '36200000']],
dtype=object)
# Otherwise you can continue to use the DataFrame for your analysis