检查列表中的特定项目,无需迭代或 find()

Lyu*_*yux 2 python python-3.x steam-web-api

所以我有一个 SteamApp 对象列表:

   >>> games
   [<SteamApp "Counter-Strike: Global Offensive" (730)>, <SteamApp "XCOM: Enemy Unknown" (200510)>]
Run Code Online (Sandbox Code Playgroud)

我也有这段代码:

ownscs = []

if '"Counter-Strike: Global Offensive"' in games:
            print('Owns CS')
            ownscs.append(foo)
Run Code Online (Sandbox Code Playgroud)

我想做的就是检查是否有人拥有《反恐精英》,但问题的关键来了,列表游戏不可迭代,并且没有属性查找,如果我尝试这两个游戏,我会得到:

if any('"Counter-strike: Global Offensive"' in s for s in games):
TypeError: argument of type 'SteamApp' is not iterable
Run Code Online (Sandbox Code Playgroud)

if games.find('"Counter-strike: Global Offensive"') != -1:
AttributeError: 'SteamApp' object has no attribute 'find'
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:当《反恐精英:全球攻势》显然既不可迭代也不可找到时,我如何检查它的游戏列表。

如果您想知道那是什么,我使用https://github.com/smiley/steamapi创建 SteamApp 对象。

Gal*_*lax 5

尽管另一个答案已经被接受,但这个替代方案更加Pythonic,并且更接近发布者的尝试:

if 'Counter-strike: Global Offensive' in (s.name for s in games):
Run Code Online (Sandbox Code Playgroud)

请注意,s.name该类的结果与 相同str(s),但我认为使用该name属性可以增加清晰度。