Python如何安全转换quoteVolume字符串为整数并过滤低交易量数据
Solution for Filtering Binance BTC Markets by Quote Volume
Hey there! Let's fix this up step by step—since you're new to Python, I'll keep things clear and avoid overly complex syntax. Your core issue is safely converting the quoteVolume string to a numeric type and filtering out low-volume entries, so let's tackle that first.
Key Issues in Your Original Code
Before diving into the fix, let's note a couple of problems that were causing errors:
- The
market_filterfunction isn't defined anywhere, so Python doesn't know how to use it. - Converting
quoteVolumedirectly without handling potential conversion failures could crash your script if any unexpected values come through the API. - Using dictionaries early on adds unnecessary complexity when we can work with lists first (easier to iterate and modify for beginners).
Fixed Code with Explanations
Here's a revised version of your code that handles the conversion safely and filters correctly:
import requests from pprint import pprint # Fetch 24hr ticker data from Binance API data = requests.get('https://www.binance.com/api/v3/ticker/24hr') data_json = data.json() # Step 1: Filter all pairs that end with "BTC" btc_markets = [market for market in data_json if market['symbol'].endswith('BTC')] # Step 2: Filter markets where quoteVolume is >= 100 (with safe conversion) high_volume_btc_markets = [] for market in btc_markets: try: # Convert quoteVolume from string to float (it can have decimal values!) quote_volume = float(market['quoteVolume']) # Only keep entries with volume >= 100 if quote_volume >= 100: high_volume_btc_markets.append(market) except ValueError: # Handle cases where quoteVolume isn't a valid number (rare, but safe to catch) print(f"Skipping invalid market {market['symbol']} - quoteVolume: {market['quoteVolume']}") # Optional: Convert the filtered list back to a dictionary if you need symbol as keys high_volume_dict = {market['symbol']: market for market in high_volume_btc_markets} print('Active high volume BTC Markets: ') pprint(high_volume_dict)
Breakdown of the Fixes
Safe Conversion with
try-except:- We use
float()instead ofint()becausequoteVolumeoften has decimal values (like your example's162.70619311). Converting to int would truncate decimals and potentially filter out valid entries. - The
try-exceptblock catches any cases wherequoteVolumeisn't a valid number (though Binance's API should always return numeric strings here, this prevents your script from crashing unexpectedly).
- We use
Simplified Filtering:
- We first use a list comprehension to grab all BTC-ending pairs—this is more readable for beginners than
dict(filter(...)). - We then iterate through each BTC market, convert the volume, and only keep entries that meet your threshold.
- We first use a list comprehension to grab all BTC-ending pairs—this is more readable for beginners than
Optional Dictionary Conversion:
- If you still need a dictionary with symbols as keys (like your original code), we can easily convert the filtered list back to a dict at the end.
Why This Works
- This approach is more robust against unexpected data and easier to debug as a new Python developer.
- It avoids unnecessary dictionary operations until the end, making the logic easier to follow.
内容的提问来源于stack exchange,提问作者normal_human
相关产品推荐
相关产品推荐

