[英]Python list loop from a index
I have a list of dic 我有一个骰子列表
MyList=[
{'Buy': 'Yes', 'date': monday, 'item': '1234'},
{'Buy': 'Yes', 'date': monday, 'item': '4'},
{'Buy': 'Yes', 'date': sunday, 'item': '134'},
{'Buy': 'Yes', 'date': sunday, 'item': '124'},
{'Buy': 'Yes', 'date': friday, 'item': '14'},
{'Buy': 'Yes', 'date': friday, 'item': '234'}
]
I use a loop 我使用循环
for data in Mylist:
so it will go through all the items 所以它将遍历所有项目
if I want to do the same but I want to choose the begin and the end of le loop for example a loop start from 0 to 3 or a loop from 2 to end how can I do that? 如果我想做同样的事情,但是我想选择le循环的开始和结束,例如从0到3的循环或从2到结束的循环,我该怎么做?
thanks in advance 提前致谢
Use slicing: 使用切片:
for data in Mylist[:3]:
or: 要么:
for data in Mylist[2:]:
Related: Python's slice notation 相关: Python的切片符号
To loop through the first n elements: 要遍历前n个元素:
for i in itertools.islice(L, 0, n):
# do stuff
To loop through the last n elements: 要遍历最后n个元素:
for i in itertools.islice(L, len(L)-n, len(L)):
# do stuff
To loop through the first n and the last m elements: 要遍历前n个和后m个元素:
for i in itertools.chain(itertools.islice(L, len(L)-n, len(L)), itertools.islice(L, len(L)-m, len(L))):
# do stuff
If you were interested in printing items 0 through 3, for example, you could do something like this: 例如,如果您对打印项目0到3感兴趣,则可以执行以下操作:
for item in MyList[:3]:
print item
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.