问题 对于第三个列表中给定数量的元素,返回两个列表之间的字符串匹配


我有一种感觉,我会被告知去参加'初学者指南'或者你有什么但我在这里有这个代码

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']

12855
2017-08-02 18:43


起源

这就像一个集合交集(截断),虽然集合没有顺序。 - smci
请注意使用订单 while 5>len(work) 被许多人视为不合逻辑,导致其名称 “尤达条件”。当然这两种方式都是正确的:) - Andras Deak
@WilliamCorrigan你应该接受你发现有帮助的答案,向其他读者表明什么有助于解决你的问题。 - idjaw


答案:


你可以尝试这样的事情:

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

您的代码的问题在于它在完成所有项目的循环后检查工作的长度 it 并添加了所有这些 does


8
2017-08-02 18:46



比我的解决方案更优化和更清晰。我删除了我的,以确保你的作品被视为最受青睐的解决方案。 +1 - idjaw
@idjaw非常感谢你!删除你的答案不需要:) - Christos
对于这种情况,我比我更喜欢你的解决方案,并希望OP看到相同的。 :) - idjaw


你可以做:

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
2017-08-02 18:52





或者,为了更接近原始逻辑:

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']

1
2017-08-02 18:53





只是为了好玩,这里是一个没有进口的单线程:

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))]

0
2017-10-01 09:08