我正试图弄清楚这个python这个python语句的括号是什么意思:
[self.bids.insert_order(bid[2], Decimal(bid[1]), Decimal(bid[0]), initial=True) for bid in json_doc['bids']]
我正在试图找出括号在这里做了什么。它是否正在修改列表?我不明白,我无法弄清楚如何向谷歌寻求正确的答案。这是完整的功能:
def get_level3(self, json_doc=None):
if not json_doc:
json_doc = requests.get('http://api.exchange.coinbase.com/products/BTC-USD/book', params={'level': 3}).json()
[self.bids.insert_order(bid[2], Decimal(bid[1]), Decimal(bid[0]), initial=True) for bid in json_doc['bids']]
[self.asks.insert_order(ask[2], Decimal(ask[1]), Decimal(ask[0]), initial=True) for ask in json_doc['asks']]
self.level3_sequence = json_doc['sequence']
答案 0 :(得分:3)
本质上它意味着:为列表中的每个项目做点什么
这是一个简单的例子:
exampleList = [1, 2, 3, 4, 5]
#for every item in exampleList, replace it with a value one greater
[item + 1 for item in exampleList]
print(exampleList)
#[2, 3, 4, 5, 6]
当您需要为列表中的每个项目执行相对简单的操作时,列表推导非常有用
[self.bids.insert_order(bid[2], Decimal(bid[1]), Decimal(bid[0]), initial=True) for bid in json_doc['bids']]
我们正在使用的列表是json_doc['bids']
。因此,对于json_doc['bids']
中的每次出价,我们都会在self.bids.insert_order()
处插入一个新出价,该出价具有该出价的所有质量,并存储为bid[0]
,bid[1]
等。总之,此列表理解为json列表中的每个出价调用函数self.bids.insert_order()
答案 1 :(得分:1)
首先,list comprehension是一种构建内联列表的方法。假设您要列出前五个方块的数字。一种方法是:
square_list = []
for i in range(1,6):
square_list.append(i**2)
# square_list = [1, 4, 9, 16, 25]
Python有一些语法糖来简化这个过程。
square_list = [i**2 for i in range(1,6)]
我认为最重要的是你的例子是有问题的代码。它使用列表推导来重复应用函数。该行生成一个列表并立即将其抛弃。在前一个示例的上下文中,它可能类似于:
square_list = []
[square_list.append(i**2) for i in range(1,6)]
这通常是一种愚蠢的结构。最好使用前两种配方中的任何一种(而不是混合它们)。在我看来,你所困惑的那条线作为一个明确的循环会更好。
for bid in json_doc['bids']:
self.bids.insert_order(bid[2], Decimal(bid[1]), Decimal(bid[0]), initial=True)
这样,很明显对象self.bids
正在被改变。另外,如果是这样写的,你可能不会问这个问题。