改进了用于在python中迭代列表中的每个项的代码,从索引(而不是0)开始
在这段代码中,我想迭代列表中的每个项目,从索引[4]开始,到索引[3]结束。有没有办法改进我编写代码以实现这一点的繁琐方式?我在[4:3]的几天内尝试了一次“迭代”,但这只迭代了索引4到6,从来没有0到3改进了用于在python中迭代列表中的每个项的代码,从索引(而不是0)开始,python,python-3.x,list,iterator,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
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)
mar=int(输入())
天数=[“0”、“1”、“2”、“3”、“4”、“5”、“6”]
计数=0
x=“0”
当计数
试试这个:
input = '4'
start_day = int(input)
days = ["0","1","2","3","4","5","6"]
days_before = []
# Loop
for day in days:
if int(day) > start_day: # Either print
print day
else:
days_before.append(day) # Or dump to second list
else: # When finished
for day in days_before: # Print second list
print day
编辑:既然你现在告诉了我们你下面的目的,我想你所需要的就是。非常感谢你的评论和建议,它非常有效。我想到了与你的建议类似的东西,即创建两个列表,所以我很高兴看到,作为python编程的新手,我的想法是正确的。请看下面你的建议n集成到我的原始代码中,以提供我正在尝试的内容
#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)
#此程序旨在查找一年中第N天(mar)的周数,前提是今年的1月1日基于用户输入(开始日)。周数为:0-周日、1-周一、2-周二、…、6-周六。给出范围为1到365的整数K。
开始日=整数(输入(“输入开始日:-”)
mar=int(输入(“输入要查找的年份第n天:-”)
计数=0
天数=[“0”、“1”、“2”、“3”、“4”、“5”、“6”]
前几天=[]
当计数开始日:
如果计数
itertools islice+循环
您可以使用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
仅建议:
注意,工具箱的此成员可能需要重要的辅助工具
存储(取决于iterable的长度)
您正在签入整个列表。请在几天内尝试一次:是的,我想根据用户特定的开始索引迭代整个列表,并根据用户特定的索引迭代次数完成。thxI已经投票,但由于我是新加入论坛的,它似乎不算。因此,您所要做的就是告诉工作日,例如,第136天对于x年,我是对的吗?为什么不使用datetime模块呢?正确。但这是一个我要完成的练习,其中日期必须用列表中给出的数字表示,并使用分配的数字返回第2天。信不信由你,我用自己拼凑的代码通过了这个练习,但我意识到它很麻烦,并一直认为必须有一种更优雅、更灵活的方式来实现这个目标。这不是一个很好的练习,但它确实让我想到了从选定的索引中迭代列表中的所有项目,这意味着我学到了一些有用的东西。明白了。Good attitudemar=10应该返回6?对逻辑的解释会更有帮助。这实际上非常好而且简洁。你能猜出“小”是什么吗?也就是说,如果超过10、100、1000、10000等,它的表现会好还是坏?@sudonym,谢谢-但只适合小规模的iterables。对不起,我还没有测试过小的含义。如果我有时间,我会做一些测试。我自己也会看一看——这对轮换用户代理很有好处(例如)
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