Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为第三个列表中给定数量的元素返回两个列表之间的字符串匹配_Python_List_Set Intersection - Fatal编程技术网

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

Python 为第三个列表中给定数量的元素返回两个列表之间的字符串匹配,python,list,set-intersection,Python,List,Set Intersection,我有一种感觉,我会被告知去“初学者指南”或你有什么,但我这里有这样的代码 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(n

我有一种感觉,我会被告知去“初学者指南”或你有什么,但我这里有这样的代码

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
对于其中的nope:
如果len(工作)<5且不在,则:
work.append(否)
其他:
打破
您的代码的问题在于,它在遍历
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']
i=0
而4>len(工作)和i
为了好玩,这里有一个没有导入的单行程序:


这就像一个集合交集(被截断),尽管集合没有顺序。请注意,使用顺序
而5>len(work)
被许多人认为是不合逻辑的,这导致了集合的名称。当然,这两种方法都是正确的:)@WilliamCorrigan你应该接受你认为有助于向其他读者指出是什么帮助解决了你的问题的答案。比我的解决方案更优化、更清晰。我删除了我的,以确保你的被清楚地视为最受欢迎的解决方案+1@idjaw非常感谢你!不需要删除您的答案:)对于这个案例,我更喜欢您的解决方案,希望OP也能看到同样的结果。:)
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))]