英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论