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

标签 python list lambda tuples list-comprehension

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/

相关文章:

java - 从功能接口(interface)中的java 8 Map Reduce中断或返回

asp.net-mvc - ASP.NET MVC : How to POST complex object with Lists to server for Update (with/without FormCollection)

haskell - 是否可以实现一个在 lambda 演算上返回 n 元组的函数?

python - 从匹配值列表中删除字典

python - 如何遍历 Python 中的元组列表?

python - SQL:更新 A,其中 B 是 C 和 D 的每个唯一组合的最大值,其中 D 是连接表的元素

Python 社交认证。用户登录创建新用户而不是使用现有用户

python - 您可以将带有参数的函数存储在列表中,然后在 Python 中调用它们吗?

mysql - 用于合并两个列表并删除重复项的 Shell 脚本

c++ - 如何在模板类中使用 lambda 作为 STL Compare 方法?