所以我有一个 SteamApp 对象列表:
>>> games
[<SteamApp "Counter-Strike: Global Offensive" (730)>, <SteamApp "XCOM: Enemy Unknown" (200510)>]
我也有这段代码:
ownscs = []
if '"Counter-Strike: Global Offensive"' in games:
print('Owns CS')
ownscs.append(foo)
我只想检查是否有人拥有 Counter-Strike 但问题的关键来了,列表游戏不可迭代并且没有找到属性,如果我尝试这两个我得到:
if any('"Counter-strike: Global Offensive"' in s for s in games):
TypeError: argument of type 'SteamApp' is not iterable
和
if games.find('"Counter-strike: Global Offensive"') != -1:
AttributeError: 'SteamApp' object has no attribute 'find'
所以我的问题是:当《反恐精英:全局攻势》显然既不可迭代也不可查找时,我该如何检查列表游戏。
我使用 https://github.com/smiley/steamapi如果您想知道它是什么,它会创建 SteamApp 对象。
最佳答案
即使另一个答案已经被接受,这个替代方案更像 Pythonic,并且更接近发帖者的尝试:
if 'Counter-strike: Global Offensive' in (s.name for s in games):
注意s.name
和str(s)
这个类有相同的结果,但是我觉得使用name
属性增加清晰度。
关于python - 在没有 Iteration 或 find() 的情况下检查列表中的特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33884680/