我正在尝试将包含 10 个值的多个列表压缩在一起。列表由迭代器创建。有时,生成的列表包含少于 10 个值甚至 0 个值。因此,有时我会遇到这样的问题:尝试将 10 个值的列表与 0 值的列表压缩在一起,或者甚至将 0 值的列表与另一个 0 值的列表压缩在一起。我试图让 python 识别具有 0 值的列表,然后用 0 填充该列表。这就是我所拥有的(第二个 URL 是问题所在):
import grequests
import json
import time
import itertools
urls3 = [
#'https://api.livecoin.net/exchange/order_book?currencyPair=RBIES/BTC&depth=5',
'https://api.livecoin.net/exchange/order_book?currencyPair=REE/BTC&depth=5',
#'https://api.livecoin.net/exchange/order_book?currencyPair=RLT/BTC&depth=5',
]
requests = (grequests.get(u) for u in urls3)
responses = grequests.map(requests)
#CellRange("B28:DJ48").clear()
def make_column(catalog_response, name):
column = []
catalog1 = list(itertools.izip_longest(catalog_response.json()[name][0:5], fillvalue='0 '))
#catalog1 = catalog_response.json()[name][0:5]
print(catalog1)
#quantities1, rates1 = list(itertools.izip_longest(*catalog1,fillvalue='0.0001')) #uncomment for print #2
#quantities1, rates1 = zip(*catalog1) #uncomment for print #2
print(quantities1)
仅为第二个链接打印出 catalog1 会产生以下输出:
[]
[([u'0.00000001', u'9907729.00000000'],), ([u'0.00000001', u'44800.00000000'],), ([u'0.00000002', u'8463566.49169284'],), ([u'0.00000002', u'3185222.59932121'],), ([u'0.00000002', u'25000.00000000'],)]
如您所见,第一个数组打印 [],它是空的。这对我来说没有意义。我用一个更简单的例子进行了试运行,它工作得很好:
import itertools
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = []
print list(itertools.izip_longest(list1,list2, fillvalue='0'))
输出如下:
[('a', '0'), ('b', '0'), ('c', '0'), ('d', '0'), ('e ', '0')]
我以为也许是运行
`column = []
catalog1 = list(itertools.izip_longest(catalog_response.json()[name][0:5], fillvalue='0 '))
#catalog1 = catalog_response.json()[name][0:5]
#print(catalog1)
quantities1, rates1 = list(itertools.izip_longest(*catalog1,fillvalue='0')) #uncomment for print #2
#quantities1, rates1 = zip(*catalog1) #uncomment for print #2
print(quantities1)`
可能会解决问题。但它返回以下错误:ValueError: need more than 0 values to unpack。我似乎无法弄清楚为什么空数组没有像我更简单的例子那样被零填充。实际上,任何用零元组列表填充空数组的方法都适用于我。如果不清楚,我深表歉意,我是编码的新手,我在这个项目上花费了大量时间,感觉自己迷失在杂草中。感谢您的帮助。
注意:这个问题与我在 How do I get my DataNitro table to either skip over failed iterations or print none to the table? 上的另一个问题直接相关但我觉得这两个问题虽然有着相同的目的,但却是截然不同的。
请您参考如下方法:
lst2 = ([[u'0',u'0'],[u'0',u'0'],[u'0',u'0'],[u'0',u'0'],[u'0',u'0']])
catalog1 = catalog_response.json()[name][0:5]
S = catalog1 + lst2
quantities1, rates1 = zip(*S)
