开发者

Python string compare issue

I've got some code that looks like this:

    valid = set()
    for string in substrings:
       for line in dictionary_words:
           if string in line:
             开发者_开发技巧  valid.add(string)
    f.writelines(sorted(valid))

Both dictionary_words and substrings are currently lists.

After the substring is found inside any dictionary_words, it should just go ahead and move onto the next substring.

What is the best way of writing that?


valid = set()
for string in substrings:
  for line in dictionary_words:
      if string in line:
          valid.add(string)
          break
f.writelines(sorted(valid))

@F.C.: If you use continue instead of break, it will run the next iteration of the inner for-loop.


Why not try this -

    valid = set()
    for string in substrings:
       if dictionary_words.has_key(string):
           valid.add(string)
    f.writelines(sorted(valid))

There is no need for the extra for-loop inside the main for-loop. This has_key solves your issue of moving on to the next substring is string is not in dictionary_word.

hope this helps...


The following (untested code) should be equivalent to your loops:

valid =  set(s for s in substrings for ln in dictionary_words if s in ln)

In Python 3.0 you could use a set comprehension:

valid = {s for s in substrings for ln in dictionary_words if s in ln}

Slightly more efficient:

valid =  set(s for s in substrings if any(s in ln for ln in dictionary_words))


[valid.add(my_string) for my_string in substrings for line in dictionary_words if my_string in line]
f.writelines(sorted(valid))

Using List Comprehensions would be faster using loops in the way you have implemented.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜