0

I want to count the occurrence of words which are followed by each other in a given list using python. E.g.

my_list = ['ABC', 'DEF', 'PQR', 'ASD', 'ABC', 'DEF', 'ZXC', 'ABC', 'PQR'] 

In the above list, the count of times when 'ABC' is followed by 'DEF' is 2.

Kindly help me out. Thanks.

khelwood
  • 52,115
  • 13
  • 74
  • 94
SubodhD
  • 306
  • 3
  • 16

2 Answers2

4

A not very efficient way to do this might be:

count = 0
for first,second in zip(my_list,my_list[1:]):
    if first == 'ABC' and second == 'DEF':
        count += 1

Or in a one-liner using sum(..):

count = sum(1 for first,second in zip(my_list,my_list[1:]) if first == 'ABC' and second == 'DEF')

Or as @khelwood says, you can exploit the fact that int(..) of a boolean returns 0 and 1:

count = sum(first == 'ABC' and second == 'DEF' for first,second in zip(my_list,my_list[1:]))
Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485
3

A straightforward way that does not involve creating an extra slice for pairwise iteration would be to simply use indexes:

sum(1 for index in range(len(my_list) - 1) 
    if my_list[index] == 'ABC' and my_list[index + 1] == 'DEF')

Or, a bit shorter (thanks to @khelwood):

sum(my_list[index] == 'ABC' and my_list[index + 1] == 'DEF' 
    for index in range(len(my_list) - 1))

Or, without sum() and expanded:

c = 0
for index in range(len(my_list) - 1):
    if my_list[index] == 'ABC' and my_list[index + 1] == 'DEF':
        c += 1

Or:

c = 0
for index in range(len(my_list) - 1):
    c += my_list[index] == 'ABC' and my_list[index + 1] == 'DEF'

Related materials for one versus the other:

Community
  • 1
  • 1
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148