use*_*653 2 python string int list max
我有一个这样的列表:
self.thislist = ['Name', 13, 'Name1', 160, 'Name2', 394]
Run Code Online (Sandbox Code Playgroud)
基本上,列表后面有一个名称和一个数字,我试图找出列表中的最高数字,即394.但出于某种原因,它选择了一个名字this.
if max(self.thislist) > 150:
this = max(self.thislist) # so this should be 394
position = self.thislist.index(this) # The index of it
temponary = position - 1 # This is so we can find the name that is associated with it
name = self.thislist[temponary] #and this retrieves the name
Run Code Online (Sandbox Code Playgroud)
例如,'Name'当它应该是394时,它会检索.因此,重点是检索与该名称相关联的名称和数字.有任何想法吗?
通过调用max,您要求它比较所有值.
在Python 2.x中,大多数值可以相互比较,即使它们的类型不同; 比较在某些任意和特定于实现的方式中是有意义的(在CPython中,它主要归结为比较类型对象本身的名称),但这对您来说很少有用.
在Python 3.x中,大多数无关类型的值无法相互比较,因此您只需获得TypeError一个无用的答案.但解决方案是一样的.
如果你想比较数字并忽略名称,你可以过滤掉所有非数字,跳过每个偶数元素,使用一个key函数将所有非数字转换为小于任何数字的数字,或几乎任何其他避免尝试的数字比较名称和数字.例如:
if max(self.thislist[1::2]) > 150:
Run Code Online (Sandbox Code Playgroud)
作为旁注,使用这样的数据结构会使很多事情变得更复杂.看起来你真正想要的不是一个交替的名字和数字的列表,而是一个将名称映射到数字的dict,或者名称 - 数字对的列表,或类似的东西.然后你可以更容易地写东西.例如,在此之后:
self.thisdict = dict(zip(self.thislist[::2], self.thislist[1::2]))
Run Code Online (Sandbox Code Playgroud)
......你可以这样做:
if max(self.thisdict.itervalues()) > 150:
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |