gpt4 book ai didi

python - 检查所有以给定字符串开头的键的字典值是否存在于一行中

转载 作者:行者123 更新时间:2023-12-05 02:01:04 26 4
gpt4 key购买 nike

我目前的编码方式不起作用,因为“全部”返回 false,因为循环时 key.startswith() 在对非所需键的迭代期间标记为 false。

基本上我想要的是检查所有以传递的字符串为前缀的键是否都有值。我想尝试用一条线来应对我自己的挑战(并不是说这样做一定更好)但感觉卡住了。实现这一目标的最佳方法是什么?

class MyPlayer():
def __init__(self):
self.player_attributes = {
"one_height": "5'8",
"one_weight": "150",
"one_age": "25",
"two_height": "5'11",
"two_weight": "160",
"two_age": None,
}
def check_if_all_values_exist(self, prefix_to_check):
if all([key.startswith(prefix_to_check) and self.player_attributes[key] != None for key in self.player_attributes.keys()]):
print("true")

Test = MyPlayer()
Test.check_if_all_values_exist("one")
Test.check_if_all_values_exist("two")

最佳答案

忽略所有类和其他部分,只看功能,这是适合您的一个类轮。

return all(v != None for k,v in player_attributes.items() if k.startswith(x))

永远记得过滤掉噪音,这样您就可以专注于真正需要的东西。然后,您就可以轻松决定是否获得了所需的结果。在上面的循环中,for 循环过滤掉所有不以 prefix_to_check 开头的键。然后很容易看出 value 是否为 None

完整的函数定义为:

def check_key(x):
player_attributes = {
"one_height": "5'8",
"one_weight": "150",
"one_age": "25",
"two_height": "5'11",
"two_weight": "160",
"two_age": None,
}

return all(v != None for k,v in player_attributes.items() if k.startswith(x))

print ('one', check_key('one'))
print ('two', check_key('two'))

输出:

one, True
two, False

关于python - 检查所有以给定字符串开头的键的字典值是否存在于一行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66811120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com