在给定第三个列表中的元素数量的情况下,返回两个列表之间匹配的字符串。

11

我有一种感觉,会被告知去看“入门指南”之类的东西,但我有这个代码:

does = ['my','mother','told','me','to','choose','the']
it = ['my','mother','told','me','to','choose','the']
work = []

while 5 > len(work):
    for nope in it:
        if nope in does:
            work.append(nope)

print (work)

我明白了

['my', 'mother', 'told', 'me', 'to', 'choose', 'the']

为什么会这样?我该如何说服它返回呢?

['my', 'mother', 'told', 'me']

这就像一个集合交集(截断),尽管集合没有顺序。 - smci
请注意,许多人认为使用顺序while 5>len(work)是不合逻辑的,导致了“尤达条件”的名称(https://en.wikipedia.org/wiki/Yoda_conditions)。当然,两种方式都是正确的:) - Andras Deak -- Слава Україні
@WilliamCorrigan 你应该接受你发现的有帮助的答案,以便告诉其他读者什么帮助解决了你的问题。 - idjaw
4个回答

8
您可以尝试这样做:

您可以尝试以下方法:

for nope in it:
   if len(work) < 5 and nope in does:
       work.append(nope)
   else:
       break

你的代码问题在于它在遍历所有it项并添加所有在does中的项之后才检查工作长度。

比我的解决方案更优化和更清晰。我删除了我的解决方案,以确保你的解决方案被清楚地看作是首选解决方案。+1 - idjaw
@idjaw非常感谢!不需要删除你的答案 :) - Christos
对于这个问题,我更喜欢你的解决方案,希望楼主也能看到同样的好处。 :) - idjaw

1

你可以做:

does = ['my','mother','told','me','to','choose','the']
it = ['my','mother','told','me','to','choose','the']
work = []
for nope in it:
    if nope in does:
        work.append(nope)
work = work[:4]
print (work)

这只是在不检查列表长度的情况下制作列表,然后将其切割并仅留下前4个元素。

1

或者,为了与您的原始逻辑保持更密切的联系:

i = 0
while 4 > len(work) and i < len(it):
    nope = it[i]
    if nope in does:
        work.append(nope)
    i += 1

# ['my', 'mother', 'told', 'me', 'to']

0

仅仅是为了好玩,这里有一个没有导入任何模块的一行代码:

does = ['my', 'mother', 'told', 'me', 'to', 'choose', 'the']
it = ['my', 'mother', 'told', 'me', 'to', 'choose', 'the']
work = [match for match, _ in zip((nope for nope in does if nope in it), range(4))]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接