-4

For example:

my_list = ["item*1", "item*2", "item*3", "item*4"]

I'd like a way to search for "item" and return 4 as item appears 4 times regardless of the extra characters.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Cxnnxr09
  • 11
  • 4

7 Answers7

5

The simplest way I could come up with is this:

sum(map(lambda x: 'item' in x, my_list))
Out[1]: 4

It basically sums the True returned every time item is found in an element of my_list

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
2

You can use count, checking each element in your list

my_list = ["item*1", "item*2", "item*3", "item*4"]

a = sum([el.count('item') for el in my_list])
print(a)

Update:

If you want "item" counted only once if it appears multiple times within elements of your list, the solution is even simpler.

a = sum(['item' in el for el in my_list])
LevB
  • 925
  • 6
  • 10
1

you can solve this in 2 ways. the first with the 'in operator and the second with the str.find() string method. and if your search is case insensetive use the str.lower() string class method.

count = 0
for word in my_list:
    if 'item' in word.lower():
        count +=1

print(count) 

or using the str.find() method but the in is prefered

 count = 0
for word in my_list:
    if word.lower().find('item') != -1:
        count +=1

print(count) 
Adam
  • 2,820
  • 1
  • 13
  • 33
1

I've made a lambda function which will return the no of times the "item" appeared in a list or sequence.

count = lambda li: sum([i.count('item') for i in li])
print(count(["item*1", "item*2", "item*3", "item*4"]))
1

You can convert the list into str and then use count method on the string to count the occurrence of the desired word in this case "item"

my_list = ["item*1", "item*2", "item*3", "item*4", 'itemitemitem']
count = ' '.join(my_list).count('item')
print(count)

This will work even if any "item" occurs more than one time like "itemitemitem"

Saad
  • 3,340
  • 2
  • 10
  • 32
0
data_is = ["item*1", "item*2", "item*3", "item*4"]
count = 0
for each in data_is:
  if 'item' in each:
    count = count +1

print(count)
developer101
  • 118
  • 7
0
my_list = ["item*1", "item*2", "item*3", "item*4", "item-oh-item-oh-item"]
n = 0
pattern = "item"
for str in my_list:
    n += str.count(pattern)
print(n)

I added an extra string to show why I use count. If the pattern could be overlapping, like searching for "coco" in "cococo", I would use regular expressions from the package regex, not the standard package re.

Serafim
  • 484
  • 3
  • 10