Simple question:
How to only extract integers (no floats) from a list of strings?
Like this:
list_1 = [['50', 'ALA', 'A', '53', '5', '4'], ['55', 'GLY', 'A', '60', '1', '6'], ['67', 'ILE', 'A', '71', '5', '5']]
To this:
list_1 = [['50', '53', '5', '4'], ['55', '60', '1', '6'], ['67', '71', '5', '5']]
Thank you.
You can use the str.isdigit
method.
>>> 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']
Note that this will not work for floating point representations of numbers.
>>> '650.43'.isdigit()
False
If you want to filter these as well, write a traditional loop.
>>> 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']
It can be done by this piece of code, it will manage floats too, handling errors and exceptions.
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]
You can try this:
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)
Output:
['50', '53', '5', '4']
You Can do this
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.