I am trying to count the number of digits for each string in list of strings:
['', '', '000000000100111101', '', '', '0000112112111101011100000000001', '', '', '', '', '',]
So the expected output I would like to get is
[0 0 18 0 0 31 0 0 0 0 0]
I was thinking about using numpy count but the data type for list of strings is list so should I be using len?
I would greatly appreciate anyone's help thank you.
CodePudding user response:
Use a list comprehension along with the len()
function:
inp = ['', '', '000000000100111101', '', '', '0000112112111101011100000000001', '', '', '', '', '',]
lengths = [len(x) for x in inp]
print(lengths) # [0, 0, 18, 0, 0, 31, 0, 0, 0, 0, 0]
CodePudding user response:
Use the map function to apply the built in len function to each number in the list, and then convert the map object to a list.
nums = ['', '', '000000000100111101', '', '', '0000112112111101011100000000001', '', '', '', '', '',]
lengths = list(map(len, nums))
print(lengths)
Output:
[0 0 18 0 0 31 0 0 0 0 0]
CodePudding user response:
The get that exact output you could do this:
L = ['', '', '000000000100111101', '', '', '0000112112111101011100000000001', '', '', '', '', '',]
print(f'[{" ".join(map(str, map(len, L)))}]')
Output:
[0 0 18 0 0 31 0 0 0 0 0]
CodePudding user response:
Use len() function along with for loop to get the count for each string inside a list. like this
newList = []
for value in values:
newList.append(len(value))
Output:
[0, 0, 18, 0, 0, 31, 0, 0, 0, 0, 0]
If you want the output without comma, you want to add a little statements like this!
anotherList = []
for value in values:
try:
if anotherList[0] != "":
anotherList[0] = str(anotherList[0]) " " str(len(value))
except IndexError:
anotherList.append(len(value))
Output:
['0 0 18 0 0 31 0 0 0 0 0']