【问题标题】:Python is not able to compare a value to a list element [duplicate]Python无法将值与列表元素进行比较[重复]
【发布时间】:2021-03-05 21:46:34
【问题描述】:

所以我对python比较陌生,不知道这里出了什么问题?我确信这是我缺少的基本东西,但不确定它可能是什么,下面是查找列表中任何数字的匹配目标的代码,这应该根据我的工作,但不是。

def abc(target,list1):
    for a in list1:
        if a == target:
            return a
        else:
            return 0
def main():
    target = input("enter target")
    list1 = []
    n = int(input("Enter number of elements : ")) 
    for i in range(0, n): 
        ele = input() 
    list1.append(ele)

g = abc(target,list1)
print(g)

if __name__== '__main__':
    main()

以下是由于代码不起作用而明显返回 0 的输出:

Enter target7
Enter number of elements : 4
5
6
7
8
0

如果列表中的值与目标匹配,它应该不返回 7

【问题讨论】:

标签: python python-3.x list function range


【解决方案1】:

如 cmets 中所述,abc() 中的逻辑已关闭。

这应该可以按预期工作:

def abc(target, list1):
    return target if target in list1 else 0


def main():
    target = int(input("enter target"))
    list1 = []
    n = int(input("Enter number of elements : "))
    for i in range(0, n):
        list1.append(int(input()))
    print(abc(target, list1))


if __name__ == '__main__':
    main()

输出:

Enter number of elements : 4
5
6
7
8
7

【讨论】:

    【解决方案2】:

    你的缩进有误:

    def abc(target,list1):
        for a in list1:
            if a == target:
                return a
            else:
                return 0
    
    
    def main():
        target = input("Enter target: ")
        list1 = []
        n = int(input("Enter number of elements: "))
        for i in range(0, n):
            ele = input(f"Enter element #{i+1}: ")
            list1.append(ele)
    
        g = abc(target,list1)
        print(g)
    
    
    if __name__== '__main__':
        main()
    
    Enter target: 2
    Enter number of elements: 1
    Enter element #1: 2
    2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多