尝试根据条件追加List / array

时间:2018-03-20 12:34:20

标签: python loops if-statement

我正在尝试根据条件添加到数组中。 有人可以澄清为什么if语句不能正常工作吗?

all_staff = ["Judith", "Harry", "Jonathan", "Reuben"]
new_staff = []


def person_finder(staff):
for x in staff:
    if x == "Reuben" or "Harry" or "Jonathan":
        new_staff.append(x)
    else:
        continue
    return new_staff


selected = person_finder(all_staff)


def the_men(people):
for x in people:
    print(x + " is a man")


the_men(selected)

返回:

朱迪思是个男人

3 个答案:

答案 0 :(得分:1)

替换

if x == "Reuben" or "Harry" or "Jonathan":

if x == "Reuben" or x == "Harry" or x == "Jonathan":

答案 1 :(得分:1)

更改此行:

if x == "Reuben" or "Harry" or "Jonathan":

if x == "Reuben" or x=="Harry" or x=="Jonathan":

工作代码:

all_staff = ["Judith", "Harry", "Jonathan", "Reuben"]

new_staff = []


def person_finder(staff):
    for x in staff:
        if x == "Reuben" or x=="Harry" or x=="Jonathan":
            new_staff.append(x)
        else:
            continue
    return new_staff


selected = person_finder(all_staff)


def the_men(people):
    for x in people:
        print(x + " is a man")


the_men(selected)

输出:

Harry is a man
Jonathan is a man
Reuben is a man

答案 2 :(得分:1)

all_staff = ["Judith", "Harry", "Jonathan", "Reuben"]


def person_finder(staff):
    new_staff = []
    for x in staff:
        if x in ["Reuben", "Harry", "Jonathan"]:
            new_staff.append(x)
        else:
            continue
    return new_staff


selected = person_finder(all_staff)


def the_men(people):
    for x in people:
        print(x + " is a man")


the_men(selected)