使用词典

时间:2017-07-05 12:19:33

标签: python list search nested

- 编辑:

好的,谢谢你们,特别是随机我调整循环如下:

while buy_active > 0 or balance_available > 0 or i <= 0:
        print('Selling {0} {1} for {2:.8f} {3}. Volume: {4} It {5}'.format(balance_available, currency, coinprice_sell, trade, coinvolume, i))
        api.selllimit(market, balance_available, coinprice_sell)

        open_order = api.getopenorders(market)
        buy_active = len(list(filter(partial(eq, "LIMIT_BUY"),
                                map(itemgetter("OrderType"), open_order)))) > 0

        coinbalance = api.getbalance(currency)
        balance_available = coinbalance['Available']  # You still have some coins available
        coinsummary = api.getmarketsummary(market)
        coinprice = coinsummary[0]['Last']
        coinvolume = coinsummary[0]['Volume'] * coinprice
        i += 1
else:
        print('No open Buy order or remaining quantity')

现在这些代码几乎一直运行完美但偶尔会收到一个错误(我不知道如何复制,因为它可能取决于API传输给程序的内容。

错误说:

Traceback (most recent call last):
  File "test.py", line 76, in <module>
    while buy_active > 0 or balance_available > 0 or i <= 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'

所以我解释了有时变量buy_active没有类型的错误,因此不能用&#34;&gt;&#34;来解释。但是,我不知道这是怎么发生的。它可能与len有关(列表(过滤器(...方法。我也尝试定义buy_active = 1,因此它至少进入循环一次。但这并不能解决问题。因此我猜这个算子有时候提供一个NoneType字符。

是否有人建议问题是什么?

最佳

SaltyJ

原件:

我刚刚开始使用python 2.7进行编程(对于这个特殊的代码,我想留在2.7)我遇到了一个问题。由于我对编程很新,我无法弄清楚如何解决我的问题。我希望你能提供帮助。

我想通过API处理有关我在线交易所的未结订单的一些输入。

通过API,我收到一个包含嵌套字典的列表。一个例子(下面是2个订单)。

{
    "success" : true,
    "message" : "",
    "result" : [{
            "Uuid" : null,
            "OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_SELL",
            "Quantity" : 5.00000000,
            "QuantityRemaining" : 5.00000000,
            "Limit" : 2.00000000,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.77",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }, {
            "Uuid" : null,
            "OrderUuid" : "8925d746-bc9f-4684-b1aa-e507467aaa99",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_BUY",
            "Quantity" : 100000.00000000,
            "QuantityRemaining" : 100000.00000000,
            "Limit" : 0.00000001,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.583",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }
    ]
}

API为每个未结订单生成一个包含一个字典的列表。

现在我想基本上让我的代码完成所有的代码。寻找字符串&#34; LIMIT_BUY&#34;。

我目前的代码最多可以执行2个订单。但它可能非常低效,也无法应对订单&gt; 2:

在循环结束时,buy_active变量应为&#34; 1&#34;如果有任何买单,如果没有订单或只有卖单,则为0。

if len(open_order) == 2:
            order_type_1 = open_order[0]['OrderType']
            order_type_2 = open_order[1]['OrderType']
            if order_type_1 == 'LIMIT_BUY' or order_type_2 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0

        elif len(open_order) == 1:
            order_type_1 = open_order[0]['OrderType']
            if order_type_1 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0
        else:
            buy_active = 0

我想要的是使用任意数量的条目查看列表的最有效(在时间方面)代码。

有人能帮助我吗?:)

非常感谢!我刚刚开始编码4天前,所以请保持良好:)

最佳

SaltyJ

3 个答案:

答案 0 :(得分:0)

这将是命令式编程方法,只需循环遍历open_order列表中的值:

buy_active = False
for order in open_order:
    if order.get("OrderType") == "LIMIT_BUY":
        buy_active = True
        break

我们使用for loop来迭代列表中的项目,然后我们safely inspect每个项目(这是一个字典) - 以查看它是否包含密钥OrderType,以及如果是,它是否等于LIMIT_BUY。当我们找到第一个这样的项目时,我们将buy_active设置为True,并中止任何进一步的处理(我们知道至少有一个项目,因此没有必要循环其他项目。)

这将是函数式编程方法:

from operator import itemgetter, eq
from functools import partial

buy_active = len(filter(partial(eq, "LIMIT_BUY"),
                        map(itemgetter("OrderType"), open_order))) > 0

如果找到至少一个buy_active作为True的值,则布尔变量LIMIT_BUY将为OrderType,与之前的方法相同。

这里我们使用名为map的内置函数来评估itemgetter("OrderType")词典集合中每个项目的函数open_orderitemgetter将从每个字典中提取"OrderType",映射的结果将是所有OrderType的列表,如下所示:["LIMIT_SELL", "LIMIT_BUY", ...]

我们现在在该列表中应用filter,并使用partially应用eq运算符检查是否有任何项目等于"LIMIT_BUY"。过滤掉所有不存在的内容,生成一个列表:["LIMIT_BUY", ...]

之后,我们只需检查列表的长度,如果列表不为空,则声明buy_activeTrue

答案 1 :(得分:0)

欢迎来到精彩的编码艺术!

你遇到了第一个重复的任务。这可能是调查for-loopswhile-loops的时候。它们允许您重复任务。

例如,虽然大大简化了:

mylist = [1,2,3]
# Your way:
print mylist[0]
print mylist[1]
print mylist[2]
# This works, but gets tedious if your list grows.

# This is way more concise:
for i in mylist:
    print i

答案 2 :(得分:0)

您可以使用any()功能和列表理解(过滤列表)。 当“OrderType”等于“LIMIT_SELL”时,列表理解会创建一个新的True值列表。

import json
data = json.loads("""{
    "success" : true,
    "message" : "",
    "result" : [{
            "Uuid" : null,
            "OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_SELL",
            ....
""")

buy_active = any([True for item in data['result'] if item['OrderType'] == 'LIMIT_BUY' ])