Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

python-3.x - 如何停止显示“ for”循环结果?(How do I stop showing the “for” loop result?)

Here is my code:

(这是我的代码:)

from functools import partial

def x_in_y(word, inner):
    return inner in word

wrong = ['mann','connaction','tee','rigt','putt']
sentence=['this mann is my son','the connaction is unstable','my tee is getting cold','put your hands down','rigt now','right behind my back']

for i in wrong:
    print(f"Wrong: {i}")
    filtered_names = filter(partial(x_in_y, inner=i), sentence)
    for name in filtered_names:
        print(name)

Please tell me how do i only show the matches without the others?

(请告诉我如何仅显示比赛而不显示其他比赛?)

(In this case, remove "wrong:putt")

((在这种情况下,请删除“ wrong:putt”))

Like:

(喜欢:)

Wrong: mann
this mann is my son
Wrong: connaction
the connaction is unstable
Wrong: tee
my tee is getting cold
Wrong: rigt
rigt now

Please help me.

(请帮我。)

  ask by briiipo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want print names only if they appear in at least one sentence, Just move the print(f"Wrong: {i}") below the filtered_names and check iterator that is empty with next() like this:

(如果只希望打印名称出现在至少一个句子中,只需将print(f"Wrong: {i}")移到filtered_names下方,然后使用next()检查为空的迭代器,如下所示:)

for i in wrong:
    filtered_names = filter(partial(x_in_y, inner=i), sentence)
    next_elem = next(filtered_names, None)
    if next_elem:
        print(f"Wrong: {i}") 
        print(next_elem)
    for name in filtered_names:
        print(name)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...