改进代码,迭代python中列表中的每个项目,从0

时间:2018-06-08 07:39:26

标签: python python-3.x list iterator

在这段代码中,我想迭代列表中的每个项目,从索引[4]开始,在索引[3]处完成。有没有办法改进我编写代码来实现这一目标的繁琐方式?我试了几天[4:3],但这只迭代索引4到6而且从不0-3;

mar = int(input())
days = ["0","1","2","3","4","5","6"]
count = 0
x = "0"
while count < mar:
  for a in days[4],[5],[6],[0],[1],[2],[3]:
    if count < mar:
      count += 1
      x = a   
print(x)

4 个答案:

答案 0 :(得分:1)

itertools islice + cycle

您可以使用itertools创建迭代器。这是一个懒惰的解决方案,需要您在指定范围内调用迭代器上的next

from itertools import islice, cycle

c = islice(cycle(days), 5, None)

for _ in range(len(days)):
    print(next(c))

5
6
0
1
2
3
4

仅推荐for small iterables

  

请注意,此工具包的成员可能需要大量辅助   存储(取决于可迭代的长度)。

答案 1 :(得分:0)

试试这个:

square[square.columns == col.name]

编辑:既然您现在告诉我们您的目的,我认为您所需要的只是this

答案 2 :(得分:0)

非常感谢您的评论和建议,它完美无缺。我正在考虑类似于你的建议,即创建两个列表,所以我很高兴看到作为python编程的新手我正在思考正确的方法。请在下面将您的建议集成到我的原始代码中,以实现我的目标;

 #This programme is intended to find the number of day of week for N-th day (mar) of a year provided that in this year January 1 is based on user entry (start_day). Days of week are numbered as: 0 — Sunday, 1 — Monday, 2 — Tuesday, ..., 6 — Saturday. An integer K in the range 1 to 365 is given.                        
start_day = int (input("Enter day number to start:- ")) 
mar = int(input("Enter nth day of the year to find:-"))    
count = 0      
days = ["0","1","2","3","4","5","6"]
days_before = []
while count < mar:
# Loop                
  for day in days: 

    if int(day) > start_day: 
      if count < mar:
        count += 1     # Either print
        print (day)    
    else:
        days_before.append(day)   # Or dump to second list
  else:                             # When finished
    for day in days_before: 
      if count < mar:
        count += 1       # Print second list
        print (day)  

答案 3 :(得分:0)

start = 4
for i in range(start, start+min(mar, len(days))):
    print(days[i % len(days)])

# mar = 4 --> 4, 5, 6, 0
# mar = 10 --> 4, 5, 6, 0, 1, 2, 3