为第三个列表中给定数量的元素返回两个列表之间的字符串匹配

我有一种感觉,我会被告知去“初学者指南”或你有什么,但是我有这里的代码为第三个列表中给定数量的元素返回两个列表之间的字符串匹配

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

以上是 为第三个列表中给定数量的元素返回两个列表之间的字符串匹配 的全部内容, 来源链接: utcz.com/qa/266832.html

回到顶部