gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:21:07 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com