November 22nd, 2012, 05:36 AM
Iterate over a list of strings.
lets say a have this list:
is it possible to iterate over this list of strings with "str.isdigit()" function somehow?
list['565', '095', '4243','3003','23D5']
or the only way is to combine all the string in the list to one big string and then use "str.isdigit()"?
thanks in advanced!
November 22nd, 2012, 06:58 AM
The shortest code to do this is exactly how say, join the list to a single string and check the string
As your question appears to be looking for alternatives, you can iterate over a list with the for loop. You can then check each item in the list contains digits in the usual way. If you and the result cumlatively this will give you the answer you want.
"".join(['565', '095', '4243','3003','23D5']).isdigit()
This makes a nice little function you can call or expand on:
If you are looking for a fancy way of doing it then the reduce function is what you are looking for but you will need to define the comparison function first
def islistdigits ( inlist ):
"inlist must contain only strings - checks each item in the list contains only digits"
listalldigits = True # default in case of an empty list
for listitem in inlist:
listalldigits = listalldigits and listitem.isdigits()
If you are using Python 3 you will need to use functools.reduce
def myand ( x , y ):
return (x or x.isdigit()) and y.isdigit()
reduce(myand,['565', '095', '4243','3003','23D5'])
As an added bonus, if you wanted to reduce the list to contain only those strings with just digits in them you could use the filter function as follows:
def onlydigits ( x ):
filter(onlydigits,['565', '095', '4243','3003','23D5'])
November 22nd, 2012, 07:21 AM
i will, of course, prefer the shrortest code.
Originally Posted by Quackajack
thanks for the help!
November 22nd, 2012, 07:26 AM
Well, the following’s not particularly long either:
all(n.isdigit() for n in ['565', '095', '4243','3003','23D5'])
My armada: openSUSE 13.2 (home desktop, home laptop, work desktop), Ubuntu 14.04 LTS (server), OpenELEC 5.0 (HTPC), Debian GNU/Linux 7.7.0 (mini laptop), Android 4.2.1 (tablet)
November 22nd, 2012, 09:22 AM
I learn something new every day. I wasn't aware of the all function
November 22nd, 2012, 10:08 AM
November 23rd, 2012, 11:31 AM
all, any, divmod. Useful functions.
[/code] are essential for python code and Makefiles!