我在使用python时遇到问题。 首先,我想将for-循环的输出存储在新变量中。 其次,我只想发出前三遍(20:00、21:00、22:00)
有人可以帮我吗?
输入:
import datetime
import time
list = ["18:00","19:00", "20:00", "21:00", "22:00", "23:00"]
lol = time.strftime("%H:%M")
for i in list:
if i > lol:
print(i)
输出:
20:00
21:00
22:00
23:00
答案 0 :(得分:2)
尝试一下:
$RollingYear = (Get-Date).AddDays(-365)
$Rolling30Days = (Get-Date).AddDays(-30)
#Clean-Up Old Backup Files
Get-ChildItem 'D:\Server_Backup\' | ForEach-Object {
if ( $_.LastWriteTime.AddDays(-365) -lt $RollingYear) {
Write-Host "I want to remove files older than a year"
Remove-Item
} Elseif ( $_.LastWriteTime.AddDays(-30) -lt $Rolling30Days -and $_.LastWriteTime.Date -ne (Get-Date -Year $_.LastWriteTime.Year, -Month $_.LastWriteTime.Month -Day 1)) {
Write-Host "I want to remove files older than 1 month, but not the first of the month"
Remove-Item
} Else {
Write-Host 'Nothing to remove'
}
}
答案 1 :(得分:0)
如果要保留for循环,可以添加一个简单的计数器:
import datetime
import time
list = ["18:00","19:00", "20:00", "21:00", "22:00", "23:00"]
lol = time.strftime("%H:%M")
counter = 0
for i in list:
if i > lol and counter < 3:
print(i)
counter += 1
另一种选择是使用列表理解,并从列表中选择前三个值。
values = [i for i in list if i > lol][:3]
答案 2 :(得分:0)
我正在对此进行布局,以使您更容易理解。 如果是python的新手,则列表理解行为之类的东西可能会变得不透明。
顺便说一句,我非常喜欢多余的打印语句,因此我可以看到代码在做什么。 当您不再需要它们时,只需将它们注释掉即可。
当然有更紧凑的方法可以做到这一点,@ [Robert Hamilton]的答案就是一个很好的例子。
import datetime
import time
list = ["18:00","19:00", "20:00", "21:00", "22:00", "23:00"]
lol = time.strftime("%H:%M")
my_new_list = [ ] # here is your new variable, we'll start empty
for i in list:
print('checking i={}, my_new_list={}'.format(i, my_new_list))
if i > lol:
if len(my_new_list) < 3:
my_new_list.append(i)
print('keeping i={} since i > lol, now my_new_list={}'.format(i, my_new_list))
else:
print('ignoring i={}, already have enough.').format(i))
else:
print('skipping i={}, since i <= lol={}'.format(i, lol))
使用效率更高的循环体(我们在发现3件东西后中断了循环):
for i in list:
if i <= lol:
continue # keep looking
# if we reach this point then i > lol.
print('keeping i={}'.format(i)
my_new_list.append(i)
if len(my_new_list) >= 3:
break