扩展“if语句”以包含else子句

2024-06-08 16:19:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我将如何扩展下面的if语句,以便逻辑包含else子句。伪代码的作用如下。你知道吗

  • 理想歌手=每个名字包含“(披头士乐队)”和(“保罗”、“洋子”或“林哥”)
  • 如果列表中没有一个名字符合这些条件,那么理想的歌手=每个包含“Mick”的名字

到目前为止,我有以下代码:

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   

Tags: 代码inifnames名字ringobeatle理想
2条回答

您可以使用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)']

以下是符合您标准的解决方案:

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

基本上我列了两张单子,一张是披头士乐队的单子,一张是米克乐队的单子。然后我取第一个不是空的列表。你知道吗

输出:

['Paul McCartney (Beatle)', 'Ringo Starr (Beatle)', 'Yoko Ono (Beatle)']

相关问题 更多 >