简体   繁体   English

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

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

I'm working with strings which have horizontal tabs in them and are trying to convert them to lists.我正在使用其中包含水平制表符的字符串,并试图将它们转换为列表。 I figured out how to convert the tabs into commas, but the two tabs at the beginning and end of the string are also being converted into indexes by re.sub .我想出了如何将制表符转换为逗号,但是字符串开头和结尾的两个制表符也被re.sub转换为索引。 This is creating an issue when using list comprehension to format the string as a list as '' is not an int .当使用列表推导将字符串格式化为列表时,这会产生一个问题,因为''不是int Is there a way forward from here?有没有从这里前进的路? I'm not really keen on manually formatting each num_string prior to feeding it to python.在将每个 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: ' '

I'd just use the built in split with no params.我只是使用没有参数的内置拆分。 python 3.8.2 seems to work out of the box. python 3.8.2 似乎开箱即用。

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

But, to directly answer your question, you could also check the 'truthiness' of the value while coercing into ints.但是,要直接回答您的问题,您还可以在强制转换为整数时检查值的“真实性”。

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]

There is probably a better way to do this, but you can manually loop through (re.sub("[\\s]{1,}", ",", x)).split(',')可能有更好的方法可以做到这一点,但您可以手动循环(re.sub("[\\s]{1,}", ",", x)).split(',')

Here's how I imagine it:这是我的想象:

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

You can add a condition to your list comprehension to completely exclude the items from your resultant list:您可以在列表理解中添加一个条件,以从结果列表中完全排除项目:

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

or if you'd like to replace them with a default value instead或者如果您想用默认值替换它们

>>> 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