首页 > 解决方案 > Foreach 循环仅在包含命名元组的列表上循环一次

问题描述

我有来自集合导入命名元组的这段代码

Device = namedtuple('Device', ['Name', 'Timestamp'])

#add samples
deviceList = [Device(Name = "alo", Timestamp="00000"), Device(Name = "lilo", Timestamp="1111"), Device(Name = "piko", Timestamp="2222")]

def findDeviceByName(listOfDevices, DeviceName):
    print(listOfDevices)
    for x in listOfDevices:
        if (DeviceName == x.Name):
            return True
        else: 
            return False

print(findDeviceByName(deviceList, "lilo")) #returnes False even if lilo is in deviceList
print(len(deviceList)) #prints 3

并且由于某种原因,这个 foreach 循环在列表中的第一个元素处停止,但是您可以清楚地看到列表中有 3 个元素,甚至 len() 也这么说

不知道为什么会这样

标签: pythonfor-loopnamedtuple

解决方案


推荐阅读