簡體   English   中英

使用 python 刪除列表中的空索引

[英]Using python to delete empty indexes within a list

我正在使用其中包含水平制表符的字符串,並試圖將它們轉換為列表。 我想出了如何將制表符轉換為逗號,但是字符串開頭和結尾的兩個制表符也被re.sub轉換為索引。 當使用列表推導將字符串格式化為列表時,這會產生一個問題,因為''不是int 有沒有從這里前進的路? 在將每個 num_string 提供給num_string之前,我並不熱衷於手動格式化每個 num_string。

>>> import re
>>> num_string = "    29    10    16    "
>>> print((re.sub("[\\s]{1,}", ",", x)).split(','))
['', '29', '10', '16', '']
>>> num_list = [int(i) for i in num_string]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
ValueError: invalid literal for int() with base 10: ' '

我只是使用沒有參數的內置拆分。 python 3.8.2 似乎開箱即用。

num_string = "    29    10    16    "
num_string.split()
['29', '10', '16']

但是,要直接回答您的問題,您還可以在強制轉換為整數時檢查值的“真實性”。

import re

num_string = "    29    10    16    "
num_list = re.sub("[\\s]{1,}", ",", num_string).split(',')
num_list = [int(i) for i in num_list if i]
[29, 10, 16]

可能有更好的方法可以做到這一點,但您可以手動循環(re.sub("[\\s]{1,}", ",", x)).split(',')

這是我的想象:

subList=(re.sub("[\\s]{1,}", ",", x)).split(',')
for item in subList:
   if not item=='':
      item=int(item)
   else:
      continue

您可以在列表理解中添加一個條件,以從結果列表中完全排除項目:

>>> num_list = [int(i) for i in num_string if i != '']

或者如果您想用默認值替換它們

>>> num_list = [int(i) if i != '' else -1 for i in num_string]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM