有没有办法仅从 python 列表中输出字符串格式的数字?

Is there a way to output the numbers, that are in string format, only from a python list?

简单问题:

如何从字符串列表中只提取整数(无浮点数)?

像这样:

list_1 = [['50', 'ALA', 'A', '53', '5', '4'], ['55', 'GLY', 'A', '60', '1', '6'], ['67', 'ILE', 'A', '71', '5', '5']]

为此:

list_1 = [['50', '53', '5', '4'], ['55', '60', '1', '6'], ['67', '71', '5', '5']]

谢谢。

您可以使用str.isdigit方法。

>>> list_1 = ['50', 'ALA', 'A', '53', '5', 'N', '4']
>>> list_1 = [x for x in list_1 if x.isdigit()]
>>> list_1
['50', '53', '5', '4']

请注意,这不适用于数字的浮点表示。

>>> '650.43'.isdigit()
False

如果你也想过滤这些,写一个传统的循环。

>>> list_1 = ['50', '650.43', 'test']
>>> result = []
>>> for x in list_1:
...     try:
...         float(x)
...         result.append(x)
...     except ValueError:
...         pass
... 
>>> result
['50', '650.43']

你可以试试这个:

list_1 = ['50', 'ALA', 'A', '53', '5', 'N', '4']

digits = []
for item in list_1:
    for subitem in item.split():
        if(subitem.isdigit()):
            digits.append(subitem)
print(digits) 

输出:

['50', '53', '5', '4']

你可以做到

list_1 = ['50', 'ALA', 'A', '53', '5', 'N', '4']
list_2 =[]
for i in range(len(list_1)):
    if list_1[i].isnumeric():
        list_2.append(list_1[i])
print(list_2) 

可以通过这段代码来完成,它也会管理浮点数,处理错误和异常。

Loop can be converted into comprehension for more Pythonic way.

def isfloat(value):
  try:
    float(value)
    return True
  except:
    return False

v = ['50', 'ALA', 'A', '53', '5', 'N', '4']
result = []
for x, i in enumerate(map(isfloat, v)):
    if i is True:
    result.append(v[x])

print result # [50, 53, 5, 4]