【发布时间】:2011-12-13 01:38:20
【问题描述】:
我想增加一个变量 - 如果满足特定条件 - 我想将迭代器的下一个元素分配给它。在这两种情况下,结果都应该附加到一个列表中。
问题是,该函数只能识别迭代器中已经存在的值。
输入数据是一个嵌套列表。
import datetime as dt
dates_prices = [[dt.datetime(2008, 6, 3, 0, 0), 48.54],
[dt.datetime(2008, 6, 6, 0, 0), 47.99]]
def fillDates(dates_prices):
filled = []
iter_data = iter(dates_prices)
item = iter_data.next()
filled.append(item)
while True:
item[0] += dt.timedelta(1)
try:
if item in dates_prices:
item = iter_data.next()
filled.append(item)
except StopIteration:
return filled
a = fillDates(dates_prices)
print a
该函数应检查原始嵌套列表中缺少哪些日期。它应该将所有缺失的日期与最后一个已知的价格点一起添加,所以输出应该是这样的:
a =
[[dt.datetime(2008, 6, 3, 0, 0), 48.54],
[dt.datetime(2008, 6, 4, 0, 0), 48.54],
[dt.datetime(2008, 6, 5, 0, 0), 48.54],
[dt.datetime(2008, 6, 6, 0, 0), 47.99]]
我错过了什么?
编辑:
我通过从嵌套列表“dates_prices”中创建一个单独的日期列表并应用 Sevenforce 的建议来更改它现在正在工作的函数。
但是,我仍然不知道为什么我的第一个解决方案不起作用。我猜变量赋值有问题。但我不知道是什么。
这是新功能:
import datetime as dt
dates_prices = [[dt.datetime(2008, 6, 3, 0, 0), 48.54], [dt.datetime(2008, 6, 6, 0, 0), 47.99]]
def fillDates(dates_prices):
filled = []
dates = [x[0] for x in dates_prices] #added this list
iter_data = iter(dates_prices)
item = iter_data.next()
filled.append(item[:])
while item[0] < dates[-1]:
item[0] += dt.timedelta(1)
if item[0] in dates: #using the new list here
item = iter_data.next()
filled.append(item[:]) #added colon here
return filled
a = fillDates(dates_prices)
print a
【问题讨论】:
-
您能否提供一个带有预期输出的示例输入?
-
输入是一个嵌套列表。我添加了示例输入并使我的代码可执行。很抱歉一开始没有这样做。
-
预期的输出是什么?
-
我放弃了“try-except”子句,因为它不再给我一个了
标签: python iterator variable-assignment