如何扩展以下if语句,以便逻辑包含else子句。伪代码的功能如下。
到目前为止,我有这段代码:
Names = ["John Lennon (Beatle)", "Paul McCartney (Beatle)", "Ringo Starr (Beatle)", "Yoko Ono (Beatle)", "Mick Jagger (Rolling Stone)", "Brian Jones (Rolling Stone)", "Alex Jones (na)", "Adam Smith (na)"]
Ideal_Singers = [n for n in Names if "Beatle" in n and ("Paul" in n or "Ringo" in n or "Yoko" in n)]
print Ideal_Singers
答案 0 :(得分:6)
您可以使用any
:
names = ["John Lennon (Beatle)", "Paul McCartney (Beatle)", "Ringo Starr (Beatle)", "Yoko Ono (Beatle)", "Mick Jagger (Rolling Stone)", "Brian Jones (Rolling Stone)", "Alex Jones (na)", "Adam Smith (na)"]
names1 = [i for i in names if any(b in i for b in ['(Beatle)', 'Paul', 'Yoko','Ringo'])]
ideal_names = names1 or [i for i in names if 'Mick' in i]
输出:
['John Lennon (Beatle)', 'Paul McCartney (Beatle)', 'Ringo Starr (Beatle)', 'Yoko Ono (Beatle)']
答案 1 :(得分:0)
这是符合您标准的解决方案:
cultofcoders:redis-oplog
基本上我制作两个列表,一个用于披头士乐队的条件,一个用于米克条件。然后我把第一个非空的列表。
输出:
Names = [
"John Lennon (Beatle)",
"Paul McCartney (Beatle)",
"Ringo Starr (Beatle)",
"Yoko Ono (Beatle)",
"Mick Jagger (Rolling Stone)",
"Brian Jones (Rolling Stone)",
"Alex Jones (na)",
"Adam Smith (na)"
]
allowed_beatles = ["Paul", "Ringo", "Yoko"]
Ideal_Singers = [
x for x in [
[n for n in Names if "Beatle" in n and any(b in n for b in allowed_beatles)],
[n for n in Names if 'Mick' in n]
]
if x
]
Ideal_Singers = Ideal_Singers[0] if Ideal_Singers else []
print Ideal_Singers