【问题标题】:Outputting a unique string when a user from a list is not a key in the Dictionary当列表中的用户不是字典中的键时输出唯一字符串
【发布时间】:2020-05-19 22:51:07
【问题描述】:

我正在尝试将“如果 name not in possible_respondents”这一行更改为“如果位于 possible_respondents 中的名称不在 favorite_languages 中,则输出此字符串。”

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }

possible_respondents = ['edward','tracy','crab', 'jen']

for name in favorite_languages.keys():
    if name not in possible_respondents:
        print(f"Please take the poll, {name.title()}!")
    else:
        print(f"Thank you for responding, {name.title()}!")

代码有效,但不是我想要的方式。

输出:

Thank you for responding, Jen!
Please take the poll, Sarah!
Thank you for responding, Edward!
Please take the poll, Phil!

我想要的输出例如是:

Thank you for responding, Jen!
Please take the poll, Tracy!
Thank you for responding, Edward!
Please take the poll, Crab!
Thank you for responding, Phil!

【问题讨论】:

  • 那你想怎么样?
  • "如果位于 possible_respondents 中的名称不在 favorite_languages 中" = "如果该名称位于 possible_respondents 中并且不在 favorite_languages 中" = if name in possible_respondents and name not in favorite_languages.
  • @Datanovice possible_respondents 中的两个条目不在原始字典中;我希望能够将这些用户应该进行投票的屏幕输出到屏幕

标签: python list loops dictionary


【解决方案1】:

有很多方法可以做到这一点,我会创建一个总名称列表,通过组合键和列表同时删除重复项来迭代。

total_names = set(list(favorite_languages.keys()) + possible_respondents)

然后像你一样迭代:

for name in total_names:
    if name not in favorite_languages.keys():
        print(f"Please take the poll, {name.title()}!")
    else:
        print(f"Thank you for responding, {name.title()}!")


Thank you for responding, Phil!
Thank you for responding, Sarah!
Thank you for responding, Jen!
Please take the poll, Tracy!
Please take the poll, Crab!
Thank you for responding, Edward!

【讨论】:

  • 谢谢你,我不知道为什么我没有这样想
  • @S.Coughing 你希望结果也包括 Sarah 吗?
【解决方案2】:

我想我知道你想问什么,如果这能回答它,请告诉我。

您现在正在遍历 favorite_languages 中的键,但您似乎想要检查 possible_respondants 并查看它们是否作为最喜欢的语言中的键存在。如果是这样,您将遍历 possible_respondants 并查看它们是否使用最喜欢的语言,基本上与您现在所拥有的相反,所以:

for name in possible_respondants:
    if name not in favorite_languages:
        print(f"Please take the poll, {name.title()}!")
    else:
        print(f"Thank you for responding, {name.title()}!")   

你也可以使用:

if name not in favorite_languages.keys()

或者:

if not favorite_languages.has_key(name):

希望这会有所帮助。

【讨论】:

  • 它有效,但是代码忽略了 Sarah 和 Phil,并且“possible_respondants”应该是“possible_respondants”:如果我这样做“如果 name not in favorite_languages.keys()”
【解决方案3】:

虽然问题似乎不清楚,但从阅读 cmets 听起来您需要遍历 possible_respondents 列表并将其与 favourite_languages.keys() 列表进行比较:

 for name in possible_respondents:
    if name not in favorite_languages.keys():
        print(f"Please take the poll, {name.title()}!")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2017-11-02
    • 1970-01-01
    • 2021-01-02
    相关资源
    最近更新 更多