将列表元素转换为元组列表

2024-10-02 12:27:24 发布

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

header =  ['chr', 'pos', 'ms01e_PI', 'ms01e_PG_al', 'ms02g_PI', 'ms02g_PG_al', 'ms03g_PI', 'ms03g_PG_al', 'ms04h_PI', 'ms04h_PG_al']

我想把上面的列表元素转换成元组列表。比如:

sample_list = [('ms01e_PI', 'ms01e_PG_al'), ('ms02g_PI', 'ms02g_PG_al'),
              'ms03g_PI', 'ms03g_PG_al'), ('ms04h_PI', 'ms04h_PG_al')]

我认为lambda或列表理解可以用一种简短而全面的方式来处理这个问题。你知道吗

sample_list = [lambda (x,y): x = a if '_PI' in a for a in header ..]

或者

[(x, y) if '_PI' and '_PG_al' in a for a in header]

有什么建议吗?你知道吗


Tags: samplelambdain列表forifpilist
3条回答

这是一种方法:

# first, filter and sort
header = sorted(i for i in header if any(k in i for k in ('_PI', '_PG_al')))

# second, zip and order by suffix
header = [(x, y) if '_PI' in x else (y, x) for x, y in zip(header[::2], header[1::2])]

# [('ms01e_PI', 'ms01e_PG_al'),
#  ('ms02g_PI', 'ms02g_PG_al'),
#  ('ms03g_PI', 'ms03g_PG_al'),
#  ('ms04h_PI', 'ms04h_PG_al')]

试试这个:

list = ['chr', 'pos', 'ms01e_PI', 'ms01e_PG_al', 'ms02g_PI', 'ms02g_PG_al', 'ms03g_PI', 'ms03g_PG_al', 'ms04h_PI', 'ms04h_PG_al']


def l_tuple(list):
    list = filter(lambda x: "PI" in x or "PG" in x, list)
    l = sorted(list, key=lambda x: len(x) and x[:4])
    return [(l[i], l[i + 1]) for i in range(0, len(l), 2)]

print(l_tuple(list))

输出

[('ms01e_PI', 'ms01e_PG_al'), ('ms02g_PI', 'ms02g_PG_al'), ('ms03g_PI', 'ms03g_PG_al'), ('ms04h_PI', 'ms04h_PG_al')]

您可以筛选列表并删除与所需分组模式不匹配的所有元素:

import re
import itertools
header =  ['chr', 'pos', 'ms01e', 'ms01e_PG_al', 'ms01e_PI', 'ms01e_PG_al', 'ms02g_PI', 'ms02g_PG_al', 'ms03g_PI', 'ms03g_PG_al', 'ms04h_PI', 'ms04h_PG_al']
new_headers = list(filter(lambda x:re.findall('^[a-zA-Z]+_[a-zA-Z]+|[a-zA-Z]+\d+[a-zA-Z]+', x), header))
final_data = [(new_headers[i], new_headers[i+1]) for i in range(0, len(new_headers), 2)]

输出:

[('ms01e', 'ms01e_PG_al'), ('ms01e_PI', 'ms01e_PG_al'), ('ms02g_PI', 'ms02g_PG_al'), ('ms03g_PI', 'ms03g_PG_al'), ('ms04h_PI', 'ms04h_PG_al')]

相关问题 更多 >

    热门问题