Tuesday, July 24, 2018

python - how to determine an integer in a string list




i have a problem if i have a string list



for example :



token=[aaa,bbb,ccc,ddd,0,eee,40,ggg,5]



how can i do to check whether token[i] is an integer




i want to see if token[i] is integer



i will put it in to a new string list by i+1:number



ex if token[4]=0 i will put it into result[5]="5:0"






sorry for explain not clear
first if i have many data

ex
39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Male, 2174, 0, 40, United-States, <=50K
50, Self-emp-not-inc, 83311, Bachelors, 13, Married-civ-spouse, Exec-managerial, Husband, White, Male, 0, 0, 13, United-States, <=50K



second i need to convert those data into specific number
ex State-gov into 2:1 Self-emp-not-inc into 2:2



however i can convert string into number but i cannot convert number into number
ex if token[4]=0 i will put it into result[5]="5:0"




for line in lines:
token=re.split(', ',line)

for i in range(0,13,1):
try:
value = int(token[i])

except ValueError:
pass
if (token[14] in '<=50K.'):

result.append('1')
if (token[14] in '>50K.'):
result[j].append('2')
if (value == true):
result.append('i+1:token[i]')
if (token[i] in '?'):
result.append('i+1:0')
if(token[i] in 'State-gov'):
result.append("2:1")
if(token[i] in 'Self-emp-not-inc'):

result.append('2:2')

Answer



You need to use isinstance if you want to check the type of entry , and if you have multitype elements in your list :



>>> token=['aaa','bbb','ccc','ddd',0,'eee',40,'ggg',5]
>>> ["{}:{}".format(i,j) for i,j in enumerate(token,1) if isinstance(j,int)]
['5:0', '7:40', '9:5']

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...