开发者

How can I add some string to a list in order to make a count word? [Python]

开发者 https://www.devze.com 2023-01-14 11:04 出处:网络
I want to simply add 开发者_高级运维some word to a list and then count how many words are in there...

I want to simply add 开发者_高级运维some word to a list and then count how many words are in there...

And check if the word isn't in the list already.

How can I do it?


A list can be used for this, but if speed is important and order doesn't matter then a set will be faster.

>>> S = set(['a', 'b', 'c'])
>>> S
set(['a', 'c', 'b'])
>>> 'b' in S
True
>>> S.add('d')
>>> S
set(['a', 'c', 'b', 'd'])
>>> S.add('b')
>>> S
set(['a', 'c', 'b', 'd'])


You can add a word to a list by calling alist.append("word") where alist is your list.

To count how many words are in the list simply use len(alist).

To check if the word isn't already in the list use if "word" not in alist:

-edit to remove references to word 'list', replacing it with 'alist'

0

精彩评论

暂无评论...
验证码 换一张
取 消