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]


有什么建议么?

最佳答案

尝试这个:

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')]

关于python - 将列表元素转换为元组列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48712098/

10-14 19:29
查看更多