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

发布于 2024-11-19 20:34:46 字数 145 浏览 2 评论 0原文

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

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

I'm writing a small NLP algorithm and I need to do the following:

For every string x in the list ["this", "this", "and", "that"], if the string x and the next string are identical, I want to print the string.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

橘虞初梦 2024-11-26 20:34:47

有时,我喜欢坚持使用老式循环:

strings = ['this', 'this', 'and', 'that']
for i in range(0, len(strings)-1):
   if strings[i] == strings[i+1]:
      print strings[i]

每个人都知道发生了什么而无需太多思考,而且相当有效......

Sometimes, I like to stick with old-fashioned loops:

strings = ['this', 'this', 'and', 'that']
for i in range(0, len(strings)-1):
   if strings[i] == strings[i+1]:
      print strings[i]

Everyone knows what's going on without much thinking, and it's fairly efficient...

无人问我粥可暖 2024-11-26 20:34:47

大多数 Pythonic 是 列表理解,它完全是为循环和测试而构建的同时:

>>> strings = ['this', 'this', 'and', 'that']

>>> [a for (a,b) in zip(strings, strings[1:]) if a==b]

['this']

或者,为了避免临时对象(h/t @9000):

>>> import itertools as it
>>> [a for (a,b) in it.izip(strings, it.islice(strings,1)) if a==b]

['this']

Most Pythonic is a list comprehension, which is exactly built for looping and testing at the same time:

>>> strings = ['this', 'this', 'and', 'that']

>>> [a for (a,b) in zip(strings, strings[1:]) if a==b]

['this']

Or, to avoid temporary objects (h/t @9000):

>>> import itertools as it
>>> [a for (a,b) in it.izip(strings, it.islice(strings,1)) if a==b]

['this']
时光匆匆的小流年 2024-11-26 20:34:47
TEST = ["this", "this", "and", "that"]
for i, s in enumerate(TEST):
   if i > 0 and TEST[i-1] == s:
      print s

# Prints "this"
TEST = ["this", "this", "and", "that"]
for i, s in enumerate(TEST):
   if i > 0 and TEST[i-1] == s:
      print s

# Prints "this"
北陌 2024-11-26 20:34:47

为什么不简单呢? :

strings = ['this', 'this', 'and', 'that', 'or', 'or', 12,15,15,15, 'end']

a = strings[0]
for x in strings:
    if x==a:
        print x
    else:
        a = x

why not simply ? :

strings = ['this', 'this', 'and', 'that', 'or', 'or', 12,15,15,15, 'end']

a = strings[0]
for x in strings:
    if x==a:
        print x
    else:
        a = x
难如初 2024-11-26 20:34:47

那是作业吗?

l = ["this", "this", "and", "that", "foo", "bar", "bar", "baz"]

for i in xrange(len(l)-1):
   try:
      if l.index(l[i], i+1) == i+1:
         print l[i]
   except ValueError:
      pass

Is that homework?

l = ["this", "this", "and", "that", "foo", "bar", "bar", "baz"]

for i in xrange(len(l)-1):
   try:
      if l.index(l[i], i+1) == i+1:
         print l[i]
   except ValueError:
      pass
锦上情书 2024-11-26 20:34:47

一般来说,如果您正在处理列表中的项目并且需要查看当前项目的邻居,那么您将需要使用 enumerate,因为 enumerate为您提供当前项目及其在列表中的位置。

与使用 zip 的方法不同,此列表理解不需要重复列表:

print [s for i, s in enumerate(test[:-1]) if s == test[i + 1]]

请注意,如果 test 中至少没有两个元素,则它会失败,并且 < code>test 必须是一个列表。 (zip 方法适用于任何可迭代对象。)

Generally speaking, if you're processing over items in a list and you need to look at the current item's neighbors, you're going to want to use enumerate, since enumerate gives you both the current item and its position in the list.

Unlike the approaches that use zip, this list comprehension requires no duplication of the list:

print [s for i, s in enumerate(test[:-1]) if s == test[i + 1]]

Note that it fails if there aren't at least two elements in test, and that test must be a list. (The zip approaches will work on any iterable.)

ㄖ落Θ余辉 2024-11-26 20:34:47

这是一种稍微不同的方法,它使用特殊的类来检测序列中的重复。然后,您实际上可以使用简单的列表理解来找到重复项。

class repeat_detector(object):
    def __init__(self, initial=None):
        self.last = initial
    def __call__(self, current):
        if self.last == current:
            return True
        self.last = current
        return False

strings = ["this", "this", "and", "that"]

is_repeat = repeat_detector()

repeats = [item for item in strings if is_repeat(item)]

Here's a little different approach that uses a special class to detect repeats in a sequence. Then you can actually find the repeats using a simple list comprehension.

class repeat_detector(object):
    def __init__(self, initial=None):
        self.last = initial
    def __call__(self, current):
        if self.last == current:
            return True
        self.last = current
        return False

strings = ["this", "this", "and", "that"]

is_repeat = repeat_detector()

repeats = [item for item in strings if is_repeat(item)]
墨洒年华 2024-11-26 20:34:47

使用 stdlib itertoolspairwise() 配方> 文档(我将在这里引用它):

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

你可以这样做:

for a, b in pairwise(L):
    if a == b:
        print a

或者使用生成器表达式:

for i in (a for a, b in pairwise(L) if a==b):
    print i

Use the recipe for pairwise() from the stdlib itertools documentation (I'll quote it here):

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

And you can do:

for a, b in pairwise(L):
    if a == b:
        print a

Or with a generator expression thrown in:

for i in (a for a, b in pairwise(L) if a==b):
    print i
我最亲爱的 2024-11-26 20:34:46
s = ["this", "this", "and", "that"]
for i in xrange(1,len(s)):
    if s[i] == s[i-1]:
        print s[i]

编辑:

作为旁注,如果您使用的是 python 3.X,请使用 range 而不是 xrange

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

EDIT:

Just as a side note, if you are using python 3.X use range instead of xrange

誰認得朕 2024-11-26 20:34:46
strings = ['this', 'this', 'and', 'that']
for a, b in zip(strings, strings[1:]):
    if a == b:
        print a
strings = ['this', 'this', 'and', 'that']
for a, b in zip(strings, strings[1:]):
    if a == b:
        print a
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文