我有一种感觉,我会被告知去参加'初学者指南'或者你有什么但我在这里有这个代码
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']
你可以尝试这样的事情:
for nope in it:
if len(work) < 5 and nope in does:
work.append(nope)
else:
break
您的代码的问题在于它在完成所有项目的循环后检查工作的长度 it
并添加了所有这些 does
。
你可以做:
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个第一元素。
或者,为了更接近原始逻辑:
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']
只是为了好玩,这里是一个没有进口的单线程:
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))]