Python 如何查看字典中某个值中的哪个数字更大?
我正在努力制作一个节目,让所有的球队都能看到胜利多于失败。 这是我迄今为止尝试过的,但我得到一个错误: 文件“C:/Users/ACER/Desktop/sfgthg.py”,第9行,在 如果c[1]>c[0]] TypeError:'list'和'str'实例之间不支持'>'。Python 如何查看字典中某个值中的哪个数字更大?,python,dictionary,Python,Dictionary,我正在努力制作一个节目,让所有的球队都能看到胜利多于失败。 这是我迄今为止尝试过的,但我得到一个错误: 文件“C:/Users/ACER/Desktop/sfgthg.py”,第9行,在 如果c[1]>c[0]] TypeError:'list'和'str'实例之间不支持'>'。 d={} while True: x=input("name of the team?(type stop if you want to stop") if x=="stop": bre
d={}
while True:
x=input("name of the team?(type stop if you want to stop")
if x=="stop":
break
y=int(input("how many losses?"))
z=int(input("how many wins?"))
d[x]=[y,z]
g=[c[0] for c in d.items() if c[1]>c[0]]
print(g)
在遍历字典
d
时,应该使用d.values()
,因为d.items()
返回键值对
g=[c[0] for c in d.values() if c[1]>c[0]]
或者更好,您可以这样捕获:
g = filter(lambda c: c[1] > c[0], d)
而且
g
将成为赢家的字典。正如其他人所提到的,使用eval可能是危险的。另外,您可以使用dict.values()
直接访问这些值,但我假设您想要创建一个新字典,因此我将使用dict.items()
以便您可以获得整个dict条目
无论如何,这应该适用于您提出的实际问题:
g = [c for c in d.items() if c[1][0] > c[1][1]]
c[0]
给出了项目的键,c[1]
给出了值,因此c[1][0]
给出了获胜的次数,c[1][1]
给出了损失的次数(假设您的数组结构为[wins,loss]
)
编辑:如果只需要团队名称,请将
[c代表c….]
更改为[c[0]代表c….]
如果要使用dict.items,可以在单独的变量中捕获密钥。
这将为您提供相应团队名称的列表:
d={'Madrid':[2,1],
'Barca':[1,2]}
g=[key for key,c in d.items() if c[1]>c[0]]
print(g)
eval是危险的!为什么在
input
上使用eval
?应该使用int(input(…)
替换g=[c[0]表示d中的c。items()如果c[1]>c[0]
与g=[key表示键,value表示d中的值。items()如果值[1]>value[0]]
@Sunny Patel感谢您的回复!我现在更改了!学校教我们如何使用eval进行写作有关更多信息,请参阅