如何读取列表中的两个元素?相关Python代码技术咨询
Fixing Your Python Code for Reading List Elements & Generating Candlestick Charts
Let’s walk through the problems in your current code and fix them to get the functionality you need:
Key Issues in the Original Code
- Incorrect indexing with
zip: When you usezip(div, pares), each loop iteration returns a tuple of paired elements (one fromdiv, one frompares)—not an index. Trying to use this tuple as an index (likepares[j]) will throw a TypeError because tuples can’t be used to index lists. - Variable name typo: You assigned
dtm=pares[j]but then referenceddfmin the Candlestick call—this is a typo that would cause a NameError. - Unnecessary index lookup: Since
zipalready pairs elements directly, you don’t need to look up elements by index at all.
Corrected Code
import plotly.graph_objects as go def ch1(div, pares): # Unpack paired elements directly from zip() for etiqueta, dfm in zip(div, pares): # Create candlestick figure with the paired label and DataFrame fig = go.Figure(data=[go.Candlestick( x=dfm['Date'], open=dfm['Open'], high=dfm['High'], low=dfm['Low'], close=dfm['Price'] )]) fig.update_layout( title=etiqueta, ) fig.show()
What Changed?
- We replaced
for j in zip(div,pares):withfor etiqueta, dfm in zip(div,pares):—this directly unpacks each pair into a label (etiquetafromdiv) and a DataFrame (dfmfrompares), which is exactly what you need for each chart. - Removed the incorrect index-based assignments (
dtm=pares[j]andetiqueta=div[j]) since we’re already getting these values directly from the zip loop. - Fixed the implicit typo by using
dfmconsistently (assumingparescontains pandas DataFrames with the required columns).
Notes to Ensure It Works
- Make sure every element in
paresis a pandas DataFrame that has the columnsDate,Open,High,Low, andPrice. - Ensure
divandparesare the same length—if one is longer than the other,zipwill stop at the shorter list’s length.
内容的提问来源于stack exchange,提问作者Pedro Puertas
相关产品推荐
相关产品推荐

