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
  • 55,782
  • 14
  • 81
  • 108
SubodhD
  • 306
  • 5
  • 16

2 Answers2

3

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
  • 443,496
  • 30
  • 428
  • 555
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
  • 462,703
  • 120
  • 1,088
  • 1,195