我正在尝试将包含10个值的多个列表压缩在一起。列表由迭代器创建。有时,生成的列表包含少于10个值甚至0个值。因此,有时会遇到尝试将10个值的列表与0个值的列表压缩在一起,甚至将0个值的列表与另一个0个值的列表压缩在一起的问题。我试图让python识别具有0值的列表,然后用0s填充该列表。这就是我所拥有的(第二个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)

关于python - 当随机列表返回空值时,如何使用ittoolstool和fillvalue压缩生成的列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45743908/

10-10 13:54
查看更多