在没有 Iteration 或 find() 的情况下检查列表中的特定项目
Check for specific Item in list without Iteration or find()
所以我有一个 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)
我只想检查是否有人拥有反恐精英
但问题的关键来了,列表游戏不可迭代并且没有找到属性,如果我尝试这两个我得到:
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 对象,如果您想知道那是什么。
您正在尝试在 SteamApp
对象列表中查找 str
(字符串)。这些 SteamApp
对象实际上有一个定义为与 str()
一起使用的方法,所以这段代码应该有效:
if "Counter-Strike: Global Offensive" in map(str,games):
print('Owns CS')
ownscs.append(foo)
请注意,我去掉了单引号(我认为它们是不必要的)并将 games
更改为 map(str,games)
。 map
将 str
应用于 games
中的每个项目,这将生成仅包含游戏名称的游戏列表。执行 list(map(str,games))
以查看该列表的样子。
尽管另一个答案已经被接受,但这个替代方案更像 Pythonic,并且更接近发帖者的尝试:
if 'Counter-strike: Global Offensive' in (s.name for s in games):
请注意 s.name
与此 class 的结果与 str(s)
相同,但我觉得使用 name
属性 会更加清晰。
所以我有一个 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)
我只想检查是否有人拥有反恐精英 但问题的关键来了,列表游戏不可迭代并且没有找到属性,如果我尝试这两个我得到:
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 对象,如果您想知道那是什么。
您正在尝试在 SteamApp
对象列表中查找 str
(字符串)。这些 SteamApp
对象实际上有一个定义为与 str()
一起使用的方法,所以这段代码应该有效:
if "Counter-Strike: Global Offensive" in map(str,games):
print('Owns CS')
ownscs.append(foo)
请注意,我去掉了单引号(我认为它们是不必要的)并将 games
更改为 map(str,games)
。 map
将 str
应用于 games
中的每个项目,这将生成仅包含游戏名称的游戏列表。执行 list(map(str,games))
以查看该列表的样子。
尽管另一个答案已经被接受,但这个替代方案更像 Pythonic,并且更接近发帖者的尝试:
if 'Counter-strike: Global Offensive' in (s.name for s in games):
请注意 s.name
与此 class 的结果与 str(s)
相同,但我觉得使用 name
属性 会更加清晰。