My Date = 2015-07-30
2015-07-31
2015-08-03
2015-08-04
2015-08-05
2015-08-06
2015-08-07
2015-08-10
2015-08-11
2015-08-12
2015-08-13
2015-08-14
如何从这里拨打每个第二个日期? 我试过这个,但这不起作用。
for i in range(0, len(Date), 2):
abc = Date[i]
答案 0 :(得分:5)
您可以写这个来从列表中获取每个其他日期(索引0,2,4,...):
Date[::2]
要获取其他日期(索引1,3,...),您可以写:
Date[1::2]
您可以查看此answer以获取切片表示法的说明。
由于Date
是一个列表,您可能需要将其称为dates
,以表明它是一个集合:
dates = """2015-07-30
2015-07-31
2015-08-03
2015-08-04
2015-08-05
2015-08-06
2015-08-07
2015-08-10
2015-08-11
2015-08-12
2015-08-13
2015-08-14""".split()
print(dates[::2])
# ['2015-07-30', '2015-08-03', '2015-08-05', '2015-08-07', '2015-08-11', '2015-08-13']
print(dates[1::2])
# ['2015-07-31', '2015-08-04', '2015-08-06', '2015-08-10', '2015-08-12', '2015-08-14']
答案 1 :(得分:1)
my_dates = ['2015-07-30', '2015-07-31', '2015-08-03', '2015-08-04', '2015-08-05', '2015-08-06', '2015-08-07', '2015-08-10', '2015-08-11', '2015-08-12', '2015-08-13', '2015-08-14']
使用list comprehension
:
print([my_dates[i] for i in range(1, len(my_dates), 2)])
输出:
['2015-07-31', '2015-08-04', '2015-08-06', '2015-08-10', '2015-08-12', '2015-08-14']
对于上面的示例代码,您可以将起始索引替换为1
并通过打印进行观察:
for i in range(1, len(my_dates), 2):
abc = my_dates[i]
print(abc)