2016-08-02 48 views
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'] 
+0

这就好比一个交集(截断),尽管集合没有顺序。 – smci

+0

请注意,使用'while 5> len(work)'命令被许多人看作是不合逻辑的,导致了[“yoda conditions”](https://en.wikipedia.org/wiki/Yoda_conditions)的名称。这当然是正确的任何方式:) –

+0

@WilliamCorrigan你应该接受你发现的答案,有助于向其他读者指出什么帮助解决了你的问题。 – idjaw

回答

8

你可以尝试这样的事:

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

与您的代码的问题是,它的工作长度的检查,通过所有具有循环后it的项目,并添加了所有does

+0

比我的解决方案更优化,更清晰。我删除了我的信息,以确保您的信息被清楚地看作是最受欢迎的解决方案。 +1 – idjaw

+0

@idjaw非常感谢你!不需要删除你的答案:) – Christos

+0

对于这种情况,我比你更喜欢你的解决方案,并希望OP看到同样的结果。 :) – 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))] 
相关问题