TransWikia.com

Возможно ли оптимизировать код Plotly?

Stack Overflow на русском Asked by avg999 on January 15, 2021

Код рисует горизонтальные линии по заданным параметрам в Plotly, но смущает количество повторяющихся строк

shapes=[dict(type='line', xref='paper', yref='y', line_width=0.8,
              x0=0, x1=1, y0=avc, y1=avc, line_color = '#A9A9A9',
              line = dict(dash='solid')),
            dict(type='line', xref='paper', yref='y', line_width=0.8,
              x0=0, x1=1, y0=mic, y1=mic, line_color = '#A9A9A9',
              line = dict(dash='dot')),
            dict(type='line', xref='paper', yref='y', line_width=0.8,
              x0=0, x1=1, y0=buyd, y1=buyd, line_color = '#A9A9A9',
              line = dict(dash='dot')),
            dict(type='line', xref='paper', yref='y', line_width=0.8,
              x0=0, x1=1, y0=selld, y1=selld, line_color = '#A9A9A9',
              line = dict(dash='dot')),
            dict(type='line', xref='paper', yref='y', line_width=0.8,
              x0=0, x1=1, y0=buyu, y1=buyu, line_color = '#A9A9A9',
              line = dict(dash='dot')),
            dict(type='line', xref='paper', yref='y', line_width=0.8,
              x0=0, x1=1, y0=sellu, y1=sellu, line_color = '#A9A9A9',
              line = dict(dash='dot')),
            dict(type='line', xref='paper', yref='y', line_width=0.8,
              x0=0, x1=1, y0=mac, y1=mac, line_color = '#A9A9A9',
              line = dict(dash='dot'))],

Возможно ли сократить до нечто подобного?:

shapes=[dict(name='candles', type='line',
      xref='paper', yref='y', line_width=0.8,
      x0=0, x1=1,
      y0=[avc, mic, buyd, selld, buyu, sellu, mac],
      y1=[avc, mic, buyd, selld, buyu, sellu, mac],
      line_color = '#A9A9A9', line = dict(dash='dot'))],

One Answer

Можно использовать list comprehension

shapes = [
    dict(name='candles', type='line',
         xref='paper', yref='y', line_width=0.8,
         x0=0, x1=1,
         y0=y,
         y1=y,
         line_color='#A9A9A9', line=dict(dash='dot'))
    for y in [avc, mic, buyd, selld, buyu, sellu, mac]
]

Correct answer by insolor on January 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP