简体   繁体   English

使用python将列表元素转换为连续的元组

[英]Convert list elements into successive tuple using python

a = [0, 18, 27, 43, 52, 65]

is the list of indices from which I want to access bigger list slicing with 是我要从中访问更大列表切片的索引列表

[0:18],[18:27],[27:43],[43:52], [52:65], [65:]

How to do it? 怎么做?

I have tried but i not get correct format 我已经尝试过,但是格式不正确

slicing = [index for index in (a[:-1])]

but that gives me [0, 18, 27, 43, 52] . 但这给了我[0, 18, 27, 43, 52]

Use zip : 使用zip

a = [0, 18, 27, 43, 52, 65]    
res = [bigger_list[x:y] for x, y in zip(a[:-1], a[1:])]

and finally, extend it: 最后,扩展它:

res.extend(bigger_list[a[-1]:])

Or to do it in a single line: 或单行执行:

res = [bigger_list[x:y] for x, y in zip(a[:-1], a[1:])] + bigger_list[a[-1]:]

After some tweaking and searching I found answer: 经过一些调整和搜索后,我找到了答案:

res = [bigger_list[i: a[ind+1]] for ind,i in enumerate(a[:-1])]

that also gives me slicing of bigger_list . 这也给了我slicing of bigger_list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM