I'm wracking my brain with this. I need to iterate through a nested list (a list of lists, so only one level of sublist) to check if an entry is a positive or negative integer. If it is, I need to convert it to an int. The catch is that some other list elements contain numbers, so I can't just convert a list element containing numbers to an int because I get an error.
I tried this:
aList = ['a3','orange','-1','33']
for aLine in aList:
for token in aLine:
if token.isdecimal() == True:
map(int, aLine)
elif token in "0123456789" and token.isalpha() == False:
map(int, aLine)
...Which did absolutely nothing to my list.
I'm hoping to get this kind of output:
['a3', 'orange', -1, 33]
An easy way to check if a string s
is an integer is by doing s.lstrip('+-').isdigit()
which returns True/False
. If the response is True
you can cast it to int(s)
which creates an integer.
You can create a new list from the responses or replace the item in the existing list if you have the index value. Here's a simple implementation.
aList = ['a3','orange','-1','33']
bList = []
for s in aList:
if s.lstrip('+-').isdigit():
bList.append(int(s.lstrip('+-'))
else:
bList.append(s)
print bList
The result of bList
is as follows
>>> bList
['a3', 'orange', -1, 33]
This probably is not the most pythonic answer but it works:
assume
x = [['2','-5'],['a23','321','x12']]
the code is:
output = []
for row in x:
temp = []
for element in row:
try:
temp.append(int(element))
except ValueError:
temp.append(element)
output.append(temp)
this gives you:
[[2, -5], ['a23', 321, 'x12']]
Anothere solution using list comprehension :
aList = ['a3', 'orange', '-1', '33']
results = [int(i) if i.lstrip('+-').isdigit() else i for i in aList]
print results
output:
['a3', 'orange', -1, 33]
Same can be achieved in one line using list comprehension. ( Let me know if you need explanation)
aList = ['a3', '14', 'orange', '-1', '33', '0']
print([int(x) if x.lstrip('-').isnumeric() else x for x in aList ])
['a3', 14, 'orange', -1, 33, 0]
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.