简体   繁体   中英

Split values separated by commas into variables in Python

I'm trying to get variables of a live trading order book using the 'python-binance' library.

depth = client.get_order_book(symbol='BTCUSDT')
print(depth)

This is the result.

'bids': [['34657.70000000', '0.57150000'], ['34655.76000000', '0.00035500'], ['34654.28000000', '0.01431800'][...]
'asks': [['34657.70000000', '0.57150000'], ['34655.76000000', '0.00035500'], ['34654.28000000', '0.01431800'][...]

The first value of each row is the price and the second one is the volume.

I would like to unify all 'price' values and 'volume' values into separate variables, so I would be able to sum all prices and all volumes separately.

Tried to find a related example using numpy or pandas but as you see, I'm such a newbie.

Thank you all

I predict you have those results in a dict.

price_vol = {}

for key in ['bids','asks']:
    for elem in depth[key]:
        price_vol[elem[0]] = elem[1]

That's it.

By the way, your exemple is wrong. You can't have same price for bids and ask positions at the same time;)

Assuming you are working with a dictionary you can use zip and a list comprehension that flattens a nested list to get what you want -

d = client.get_order_book(symbol='EURUSD')

bp, bv, ap, av = [j for i in d.values() for j in list(zip(*i))]

print('bids price:', bp)
print('bids volume:', bv)
print('asks price:', ap)
print('asks volume:', av)
bids price: ('34657.70000000', '34655.76000000', '34654.28000000')
bids volume: ('0.57150000', '0.00035500', '0.01431800')
asks price: ('34657.70000000', '34655.76000000', '34654.28000000')
asks volume: ('0.57150000', '0.00035500', '0.01431800')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM