根据先前的项目将列表分成两个相等的长度[python]

扎眼的阳光 python 415

原文标题Split list into two equal length based on the prevous items [python]

我有一个清单:

l_html_pdf = ['http://fund.eastmoney.com/gonggao/000060,AN201408290006828315.html',
 'http://pdf.dfcfw.com/pdf/H2_AN201408290006828315_1.pdf',
 'http://fund.eastmoney.com/gonggao/000060,AN201408280006817950.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201407170006375136.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201404190005463448.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201403310005349643.html',
 'http://pdf.dfcfw.com/pdf/H2_AN201403310005349643_1.pdf',
 'http://fund.eastmoney.com/gonggao/000060,AN201403280005340354.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201401210005016082.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201310220004535166.html']

如何将l_html_pdf分成两个等长的列表:

l_html = ['http://fund.eastmoney.com/gonggao/000060,AN201408290006828315.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201408280006817950.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201407170006375136.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201404190005463448.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201403310005349643.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201403280005340354.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201401210005016082.html',
 'http://fund.eastmoney.com/gonggao/000060,AN201310220004535166.html']

l_pdf = ['http://pdf.dfcfw.com/pdf/H2_AN201408290006828315_1.pdf',
 '',
 '',
 '',
 'http://pdf.dfcfw.com/pdf/H2_AN201403310005349643_1.pdf',
 '',
 '',
 '']

一些 HTML 链接没有对应的 PDF 链接。所以,我想把''项分配给l_pdf

原文链接:https://stackoverflow.com//questions/71476567/split-list-into-two-equal-length-based-on-the-prevous-items-python

回复

我来回复
  • Yagami_Light的头像
    Yagami_Light 评论
    pdf_links = [x if ".pdf" in x else " " for x in l_html_pdf]
    

    为了获得pdf链接。

    Out[3]: 
    [' ',
     'http://pdf.dfcfw.com/pdf/H2_AN201408290006828315_1.pdf',
     ' ',
     ' ',
     ' ',
     ' ',
     'http://pdf.dfcfw.com/pdf/H2_AN201403310005349643_1.pdf',
     ' ',
     ' ',
     ' ']
    
    html_links = [x  for x in l_html_pdf if ".html" in x ]
    

    对于使用列表理解的 html 链接

    Out[5]: 
    ['http://fund.eastmoney.com/gonggao/000060,AN201408290006828315.html',
     'http://fund.eastmoney.com/gonggao/000060,AN201408280006817950.html',
     'http://fund.eastmoney.com/gonggao/000060,AN201407170006375136.html',
     'http://fund.eastmoney.com/gonggao/000060,AN201404190005463448.html',
     'http://fund.eastmoney.com/gonggao/000060,AN201403310005349643.html',
     'http://fund.eastmoney.com/gonggao/000060,AN201403280005340354.html',
     'http://fund.eastmoney.com/gonggao/000060,AN201401210005016082.html',
     'http://fund.eastmoney.com/gonggao/000060,AN201310220004535166.html']
    
    2年前 0条评论