将一个列表分成N部分,以获得一个元组列表。

huangapple go评论78阅读模式
英文:

Splitting a list into N parts to get a list of tuples

问题

我有一个列表,我需要将其分成9个部分,但我得到了一个嵌套列表,我想要得到一个元组的列表。我不知道我是否可以在Python中做到这一点。

data = [1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', '2020-01-03', 2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', '2020-01-03']

我尝试过这个:

data = [tuple(data[i:i+9]) for i in range(0, len(data), 9)]

我得到了这个:

data = [(1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', '2020-01-03'), (2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', '2020-01-03')]

但是,我想要得到这个:

data = [(1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', '2020-01-03'), (2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', '2020-01-03')]
英文:

I've a list in which I have to split it in 9 parts but I got a list of lists, and I want to get a list of tuples. I don´t know if I can do this on python.

data= [1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', 2020-01-03, 2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', 2020-01-03]

I tried this:

data = [data[i:i+9] for i in range(0, len(data),9)]

I got this:

data= [[1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', 2020-01-03],[ 2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', 2020-01-03]]

But, I want to get this:

data= [(1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', 2020-01-03),(2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', 2020-01-03)]

答案1

得分: 2

以下是翻译好的部分:

你的解决方案几乎已经完成,你只需要转换为 tuple

data = [tuple(data[i:i+9]) for i in range(0, len(data), 9)]
            ^                ^
            这将把内部的列表转换为元组
>>> [tuple(data[i:i+9]) for i in range(0, len(data), 9)]
>>> [(1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', '2020-01-03'), (2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', '2020-01-03')]
英文:

Your solution is almost finished, you can just convert to tuple:

data = [tuple(data[i:i+9]) for i in range(0, len(data),9)]
        ^                ^
        this will convert inner lists to tuples

> >>> [tuple(data[i:i+9]) for i in range(0, len(data),9)]
> [(1, 'PURECO', 'WOMAN', 'MARISCAL', 'MULLER', 28, 'DIABETES', 'APC', '2020-01-03'), (2, 'CAO', 'WOMAN', 'CAL Y MAYOR', 'URTIZ', 34, 'OBESIDAD TIPO 1', 'APC', '2020-01-03')]

答案2

得分: 0

可以尝试这样做:

list_of_tuples = [tuple(item) for item in data]
英文:

You can try this:

list_of_tuples = [tuple(item) for item in data]

huangapple
  • 本文由 发表于 2020年1月4日 12:35:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/59587914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定