如何将字符串与列表中的下一个字符串进行比较?

avi*_*al 2 python string compare list next

我正在编写一个小型NLP算法,我需要执行以下操作:

对于列表中的每个字符串x ["this", "this", "and", "that"],如果字符串x和下一个字符串相同,我想打印字符串.

GWW*_*GWW 6

s = ["this", "this", "and", "that"]
for i in xrange(1,len(s)):
    if s[i] == s[i-1]:
        print s[i]
Run Code Online (Sandbox Code Playgroud)

编辑:

正如旁注,如果你使用python 3.X使用range而不是xrange


Fog*_*ird 5

strings = ['this', 'this', 'and', 'that']
for a, b in zip(strings, strings[1:]):
    if a == b:
        print a
Run Code Online (Sandbox Code Playgroud)

  • 如果您需要迭代一个巨大的列表(大于 RAM),您可以使用 `izip()` 代替 `zip()` 和 `islice(strings, 1, None)` 代替 `strings[1:]` ,全部来自“itertools”。 (4认同)