假設您有一個字串串列,如下所示:
the_list = ['02:00', ' GBP', '', 'Construction Output (MoM) (Jan)', '1.1%', '0.5%', '2.0%', '',
'02:00', ' GBP', '', 'U.K. Construction Output (YoY) (Jan)', '9.9%', '9.2%', '7.4%', '',
'02:00', ' GBP', '', 'GDP (MoM)', '0.8%', '0.2%', '-0.2%', '',
'02:00', ' GBP', '', 'GDP (YoY)', '10.0%', '9.3%', '6.0%', '',
'02:00', ' GBP', '', 'Index of Services', '1.0%', ' ', '1.2%', '']
每8個元素出現一次'',這是一個空字串,它恰好是存在于被呼叫的那個旁邊的同一個空字串 GBP
如何the_list更新變數以洗掉字串陣列中'' 每 8 個元素出現的元素?
uj5u.com熱心網友回復:
如果我理解正確,您可以使用 list-comprehension 過濾掉特定索引處的值:
new_list = [word for idx, word in enumerate(the_list, 1) if idx % 8 != 0]
print(new_list)
印刷:
['02:00', ' GBP', '', 'Construction Output (MoM) (Jan)', '1.1%', '0.5%', '2.0%',
'02:00', ' GBP', '', 'U.K. Construction Output (YoY) (Jan)', '9.9%', '9.2%', '7.4%',
'02:00', ' GBP', '', 'GDP (MoM)', '0.8%', '0.2%', '-0.2%',
'02:00', ' GBP', '', 'GDP (YoY)', '10.0%', '9.3%', '6.0%',
'02:00', ' GBP', '', 'Index of Services', '1.0%', ' ', '1.2%']
uj5u.com熱心網友回復:
這很簡單:
del the_list[::8] # or del the_list[7::8] if you try to delete the 7th element of each line
uj5u.com熱心網友回復:
只需使用此代碼查找在這種情況下要洗掉的元素是空字串,在 python 中是假字串,所以
for x in the_list:
if not x:
the_list.remove(x)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441600.html
