简体   繁体   中英

Python number of elements inside a list

I have a list of numeric strings, like this :

MyList = ['1','2','3 4 5 6 7','33333']

I want to check for every cell inside the list the number of objects it obtains. I used len() for every cell but it returns me the string length which is what is supposed to do I guess. I want for example to get for :

MyList[0] ~> 1
MyList[1] ~> 1
MyList[2] ~> 5
MyList[3] ~> 1

Should I cast every element to check if it returns a number and if not loop through the cell ? Or is there some function that does the trick ?

Thanks.

Assuming all are separated by whitespace you can use split :

MyList = ['1','2','3 4 5 6 7','33333']
print [len(x.split()) for x in MyList ]
[1, 1, 5, 1]

Use split and count count number of items

>>> MyList = ['1','2','3 4 5 6 7','33333']
>>> [len(itm.split()) for itm in MyList]
[1, 1, 5, 1]

The split splits a string at whitespace into substrings:

>>> "3 4 5 6 7".split()
["3", "4", "5", "6", "7"]

Assuming there's exactly one space between the elements, this will work:

counts = [cell.count(' ')+1 for cell in MyList]

And will be significantly faster than the len(cell.split()) methods.

It looks like you want to determine the number of numbers separated by spaces in each string. You can split a string by spaces with the split function. So MyList[2].split() == ['3', '4', '5', '6', '7'] and MyList[3].split() == ['33333'] . Then to check how long these are, you can use the len function. Putting it all together with list comprehensions you get

counts = [len(number_string.split()) for number_string in MyList]

And counts will have the value [1, 1, 5, 1] .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM