我有一种感觉,我会被告知去初学者指南'或者你有什么,但我在这里有这个代码
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 :(得分:8)
您可以尝试这样的事情:
ABC XUAS BSNMM
CVD nbvn nbmsb
SVDB NBV KJHA
TTS MNMN NBA
您的代码存在的问题是,在完成for nope in it:
if len(work) < 5 and nope in does:
work.append(nope)
else:
break
的所有项目并添加it
中的所有项目后,它会检查工作的长度。
答案 1 :(得分: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个第一元素。
答案 2 :(得分: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']
答案 3 :(得分: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))]